//
// Tests for System.Web.UI.WebControls.GridView.cs
//
// Author:
//	Tal Klahr (talk@mainsoft.com)
//	Yoni Klain (yonik@mainsoft.com)
//
// (C) 2005 Mainsoft Corporation (http://www.mainsoft.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// NOT TESTED :
// ondatasourceviewchanged(),onpagepreload(),RaiseCallbackEvent(),RaisePostbackEvent  


#if NET_2_0


using NUnit.Framework;
using System;
using System.IO;
using System.Globalization;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using MonoTests.SystemWeb.Framework;
using MonoTests.stand_alone.WebHarness;
using MyWebControl = System.Web.UI.WebControls;
using System.Data;
using System.Drawing;
using System.Threading;
using System.Collections.Generic;

namespace MonoTests.System.Web.UI.WebControls
{
	class PokerGridView : GridView
	{
		public bool ifPagerInitilized;
		public bool dataPropertyChanged;
		public bool pagePreLoad;
		public bool controlHierarchy;

		public PokerGridView ()
		{
			TrackViewState ();
		}

		public object SaveState ()
		{
			return SaveViewState ();
		}

		public void LoadState (object o)
		{
			LoadViewState (o);
		}

		public StateBag StateBag
		{
			get { return base.ViewState; }
		}

		public HtmlTextWriterTag PTagKey
		{
			get { return base.TagKey;}
		}

		public string Render ()
		{
			StringWriter sw = new StringWriter ();
			HtmlTextWriter tw = new HtmlTextWriter (sw);
			Render (tw);
			return sw.ToString ();
		}

		public AutoGeneratedField DoCreateAutoGeneratedColumn (AutoGeneratedFieldProperties fieldProperties)
		{
			return base.CreateAutoGeneratedColumn (fieldProperties);
		}

		public int DoCreateChildControls (IEnumerable dataSource, bool dataBinding)
		{
			return base.CreateChildControls (dataSource, dataBinding);
		}

		public Table DoCreateChildTable ()
		{
			return base.CreateChildTable ();
		}

		public ICollection DoCreateColumns (PagedDataSource dataSource, bool useDataSource)
		{
			return base.CreateColumns (dataSource, useDataSource);
		}

		public Style DoCreateControlStyle ()
		{
			return base.CreateControlStyle ();
		}

		public DataSourceSelectArguments DoCreateDataSourceSelectArguments ()
		{
			return CreateDataSourceSelectArguments();
		}

		public DataSourceView DoGetData ()
		{
			return GetData ();
		}

		public GridViewRow doCreateRow (int rowIndex, int dataSourceIndex, DataControlRowType rowType, DataControlRowState rowState)
		{
			return base.CreateRow (rowIndex, dataSourceIndex, rowType, rowState);
		}

		public string doGetCallbackResult ()
		{
			return base.GetCallbackResult ();
		}

		public string doGetCallbackScript (IButtonControl buttonControl, string argument)
		{
			return base.GetCallbackScript (buttonControl, argument);
		}

		protected override void InitializePager (GridViewRow row, int columnSpan, PagedDataSource pagedDataSource)
		{
			base.InitializePager (row, columnSpan, pagedDataSource);
			ifPagerInitilized = true;
		}

		protected override void InitializeRow (GridViewRow row, DataControlField[] fields)
		{
			base.InitializeRow (row, fields);
		}

		public bool DoOnBubbleEvent (object source, EventArgs e)
		{
			return base.OnBubbleEvent (source, e);
		}

		public void DoOnDataBinding (EventArgs e)
		{
			base.OnDataBinding (e);
		}

		public void DoOnDataBound (EventArgs e)
		{
			base.OnDataBound (e);
		}

		protected override void OnDataPropertyChanged ()
		{
			base.OnDataPropertyChanged ();
			dataPropertyChanged = true;
		}

		public void DoOnDataSourceViewChanged (object sender, EventArgs e)
		{
			base.OnDataSourceViewChanged (sender, e);
		}

		public void DoOnInit (EventArgs e)
		{
			base.OnInit (e);
		}

		public void DoOnLoad (EventArgs e)
		{
			base.OnLoad (e);
		}

		public void DoOnPageIndexChanged (EventArgs e)
		{
			base.OnPageIndexChanged (e);
		}

		public void DoOnPageIndexChanging (GridViewPageEventArgs e)
		{
			base.OnPageIndexChanging (e);
		}

		protected override void OnPagePreLoad (object sender, EventArgs e)
		{
			base.OnPagePreLoad (sender, e);
			pagePreLoad = true;
		}

		public void DoOnPreRender (EventArgs e)
		{
			base.OnPreRender (e);
		}

		public void DoOnRowCancelingEdit (GridViewCancelEditEventArgs e)
		{
			base.OnRowCancelingEdit (e);
		}

		public void DoOnRowCommand (GridViewCommandEventArgs e)
		{
			base.OnRowCommand (e);
		}

		public void DoOnRowCreated (GridViewRowEventArgs e)
		{
			base.OnRowCreated (e);
		}

		public void DoOnRowDataBound (GridViewRowEventArgs e)
		{
			base.OnRowDataBound (e);
		}

		public void DoOnRowDeleted (GridViewDeletedEventArgs e)
		{
			base.OnRowDeleted (e);
		}

		public void DoOnRowDeleting (GridViewDeleteEventArgs e)
		{
			base.OnRowDeleting (e);
		}

		public void DoOnRowEditing (GridViewEditEventArgs e)
		{
			base.OnRowEditing (e);
		}

		public void DoOnRowUpdated (GridViewUpdatedEventArgs e)
		{
			base.OnRowUpdated (e);
		}

		public void DoOnRowUpdating (GridViewUpdateEventArgs e)
		{
			base.OnRowUpdating (e);
		}

		public void DoOnSelectedIndexChanged (EventArgs e)
		{
			base.OnSelectedIndexChanged (e);
		}

		public void DoOnSelectedIndexChanging (GridViewSelectEventArgs e)
		{
			base.OnSelectedIndexChanging (e);
		}

		public void DoOnSorted (EventArgs e)
		{
			base.OnSorted (e);
		}

		public void DoOnSorting (GridViewSortEventArgs e)
		{
			base.OnSorting (e);
		}

		public void DoOnUnload (EventArgs e)
		{
			base.OnUnload (e);
		}

		public void DoPerformDataBinding (IEnumerable data)
		{
			base.PerformDataBinding (data);
		}

		protected override void PrepareControlHierarchy ()
		{
			base.PrepareControlHierarchy ();
			controlHierarchy = true;
		}

		public object DoSaveControlState ()
		{
			return base.SaveControlState ();
		}

		public void DoLoadControlState (object savedState)
		{
			base.LoadControlState (savedState);
		}

		public void SetRequiresDataBinding (bool value)
		{
			RequiresDataBinding = value;
		}

		public bool GetRequiresDataBinding ()
		{
			return RequiresDataBinding;
		}
	}

	[Serializable]
	[TestFixture]
	public class GridViewTest
	{
		class DS : ObjectDataSource, IDataSource
		{
			public static List<string> GetList ()
			{
				List<string> list = new List<string> ();
				list.Add ("Norway");
				list.Add ("Sweden");
				list.Add ("France");
				list.Add ("Italy");
				list.Add ("Israel");
				list.Add ("Russia");
				return list;
			}

			public void DoRaiseDataSourceChangedEvent (EventArgs e)
			{
				RaiseDataSourceChangedEvent (e);
			}
		}

		public class DataSourceObject
		{
			public static List<string> GetList (string sortExpression, int startRowIndex, int maximumRows)
			{
				return GetList ();
			}

			public static List<string> GetList (int startRowIndex, int maximumRows)
			{
				return GetList ();
			}

			public static List<string> GetList (string sortExpression)
			{
				return GetList ();
			}

			public static List<string> GetList ()
			{
				List<string> list = new List<string> ();
				list.Add ("Norway");
				list.Add ("Sweden");
				list.Add ("France");
				list.Add ("Italy");
				list.Add ("Israel");
				list.Add ("Russia");
				return list;
			}

			public static int GetCount ()
			{
				return GetList ().Count;
			}
		}
		
		public class data
		{
			private static ArrayList _data = new ArrayList ();

			static data ()
			{
				_data.Add (new DataItem (1, "heh1"));
				_data.Add (new DataItem (2, "heh2"));
			}

			public data ()
			{
			}

			public ArrayList GetAllItems ()
			{
				return _data;
			}

			public void UpdateItem (int id, string name)
			{
				foreach (DataItem i in _data) {
					if (i.ID == id) {
						i.Name = name;
						return;
					}
				}
			}
		}

		public class DataItem
		{
			int _id = 0;
			string _name = "";

			public DataItem (int id, string name)
			{
				_id = id;
				_name = name;
			}

			public int ID {
				get { return _id; }
			}

			public string Name {
				get { return _name; }
				set { _name = value; }
			}
		}

		public const string BOOLFIELD = "bool";
		public const string STRINGFIELD = "str";
		ArrayList myds = new ArrayList ();
		public bool InitilizePager;

		[TestFixtureSetUp]
		public void GridViewInit ()
		{

			myds.Add ("Norway");
			myds.Add ("Sweden");
			myds.Add ("France");
			myds.Add ("Italy");
			myds.Add ("Israel");
			myds.Add ("Russia");
#if VISUAL_STUDIO
			WebTest.CopyResource (GetType (), "MonoTests.System.Web.UI.WebControls.Resources.GridViewUpdate.aspx", "GridViewUpdate.aspx");
			WebTest.CopyResource (GetType (), "MonoTests.System.Web.UI.WebControls.Resources.NoEventValidation.aspx", "NoEventValidation.aspx");
			WebTest.CopyResource (GetType (), "MonoTests.System.Web.UI.WebControls.Resources.TableSections_Bug551666.aspx", "TableSections_Bug551666.aspx");
			WebTest.CopyResource (GetType (), "MonoTests.System.Web.UI.WebControls.Resources.TableSections_Bug551666.aspx.cs", "TableSections_Bug551666.aspx.cs");
			WebTest.CopyResource (GetType (), "MonoTests.System.Web.UI.WebControls.Resources.GridView_Bug595567.aspx", "GridView_Bug595567.aspx");
#else
			WebTest.CopyResource (GetType (), "GridViewUpdate.aspx", "GridViewUpdate.aspx");
			WebTest.CopyResource (GetType (), "NoEventValidation.aspx", "NoEventValidation.aspx");
			WebTest.CopyResource (GetType (), "TableSections_Bug551666.aspx", "TableSections_Bug551666.aspx");
			WebTest.CopyResource (GetType (), "TableSections_Bug551666.aspx.cs", "TableSections_Bug551666.aspx.cs");
			WebTest.CopyResource (GetType (), "GridView_Bug595567.aspx", "GridView_Bug595567.aspx");
#endif
		}

		[Test (Description="Bug 595567")]
		public void HeaderFooterVisibility_Bug595567 ()
		{
			WebTest t = new WebTest ("GridView_Bug595567.aspx");
			string originalHtml = @"<div> 
	<table id=""gridView"" cellspacing=""0"" rules=""all"" border=""1"" style=""border-collapse:collapse;""> 
			<tr> 
				<th scope=""col"">Item</th> 
			</tr><tr> 
				<td>0</td> 
			</tr><tr> 
				<td>0</td> 
			</tr><tr> 
				<td>0</td> 
			</tr> 
		</table> 
	</div>";
			string pageHtml = t.Run ();
			string renderedHtml = HtmlDiff.GetControlFromPageHtml (pageHtml);
  
			HtmlDiff.AssertAreEqual (originalHtml, renderedHtml, "#A1");
		}

		[Test]
		public void GridView_DefaultProperties ()
		{
			PokerGridView g = new PokerGridView ();
			Assert.AreEqual (0, g.StateBag.Count, "ViewState.Count");
			Assert.AreEqual (false, g.AllowPaging, "AllowPaging");
			Assert.AreEqual (false, g.AllowSorting, "AllowSorting");
			// The AlternatingRowStyle property is tested by the TableItemStyle test (already exists)
			Assert.AreEqual (true, g.AutoGenerateColumns, "AutoGenerateColumns");
			Assert.AreEqual (false, g.AutoGenerateDeleteButton, "AutoGenerateDeleteButton");
			Assert.AreEqual (false, g.AutoGenerateEditButton, "AutoGenerateEditButton");
			Assert.AreEqual (false, g.AutoGenerateSelectButton, "AutoGenerateSelectButton");
			Assert.AreEqual ("", g.BackImageUrl, "BackImageUrl");
			Assert.AreEqual (null, g.BottomPagerRow, "BottomPagerRow");
			Assert.AreEqual ("", g.Caption, "Caption");
			Assert.AreEqual (TableCaptionAlign.NotSet, g.CaptionAlign, "CaptionAlign");
			Assert.AreEqual (-1, g.CellPadding, "CellPadding");
			Assert.AreEqual (0, g.CellSpacing, "CellSpacing");
			// ToDo: The Columns property default value is tested by the DataControlFieldCollection and DataControlField tests
			Assert.AreEqual (0, g.DataKeyNames.Length, "DataKeyNames");
			// ToDo: The DataKeys property default value is tested by the DataKeyArray and DataKey tests
			Assert.AreEqual (-1, g.EditIndex, "EditIndex");
			// The EditRowStyle property is tested by the TableItemStyle test (already exists)
			// The EmptyDataRowStyle property is tested by the TableItemStyle test (already exists)
			Assert.AreEqual (null, g.EmptyDataTemplate, "EmptyDataTemplate");
			Assert.AreEqual ("", g.EmptyDataText, "EmptyDataText");
			Assert.AreEqual (false, g.EnableSortingAndPagingCallbacks, "EnableSortingAndPagingCallbacks");
			
			// The FooterStyle property is tested by the TableItemStyle test (already exists)
			Assert.AreEqual (GridLines.Both, g.GridLines, "GridLines");
			// The HeaderStyle property is tested by the TableItemStyle test (already exists)
			Assert.AreEqual (HorizontalAlign.NotSet, g.HorizontalAlign, "HorizontalAlign");
			
			Assert.AreEqual (0, g.PageIndex, "PageIndex");
			// ToDo: The PagerSettings property is tested by the PagerSettings test
			// The PagerStyle property is tested by the TableItemStyle test (already exists)
			Assert.AreEqual (null, g.PagerTemplate, "PagerTemplate");
			Assert.AreEqual (10, g.PageSize, "PageSize");
			Assert.AreEqual ("", g.RowHeaderColumn, "RowHeaderColumn");
			// ToDo: The Rows property is tested by the GridViewRowCollection and GridViewRow test
			// The RowStyle property is tested by the TableItemStyle test (already exists)
			Assert.AreEqual (false, g.ShowFooter, "ShowFooter");
			Assert.AreEqual (true, g.ShowHeader, "ShowHeader");
			Assert.AreEqual (SortDirection.Ascending, g.SortDirection, "SortDirection");
			Assert.AreEqual (null, g.TopPagerRow, "TopPagerRow");
			Assert.AreEqual (true, g.UseAccessibleHeader, "UseAccessibleHeader");
		}

		[Test]
		public void GridView_DefaultPropertiesNotWorking ()
		{
			PokerGridView g = new PokerGridView ();
			Assert.AreEqual (null, g.FooterRow, "FooterRow");
			Assert.AreEqual (null, g.HeaderRow, "HeaderRow");
			Assert.AreEqual (true, g.Visible, "ViewVisible");
			Assert.AreEqual (0, g.PageCount, "PageCount");
			Assert.AreEqual ("", g.SortExpression, "SortExpression");
		}

		[Test]
		public void GridView_AssignedProperties ()
		{
			PokerGridView g = new PokerGridView ();
			Assert.AreEqual (0, g.StateBag.Count, "ViewState.Count");
			g.AllowPaging = true;
			Assert.AreEqual (true, g.AllowPaging, "AllowPaging");
			g.AllowSorting = true;
			Assert.AreEqual (true, g.AllowSorting, "AllowSorting");
			g.AutoGenerateColumns = false;
			Assert.AreEqual (false, g.AutoGenerateColumns, "AutoGenerateColumns");
			g.AutoGenerateDeleteButton = true;
			Assert.AreEqual (true, g.AutoGenerateDeleteButton, "AutoGenerateDeleteButton");
			g.AutoGenerateEditButton = true;
			Assert.AreEqual (true, g.AutoGenerateEditButton, "AutoGenerateEditButton");
			g.AutoGenerateSelectButton = true;
			Assert.AreEqual (true, g.AutoGenerateSelectButton, "AutoGenerateSelectButton");
			g.BackImageUrl = "test";
			Assert.AreEqual ("test", g.BackImageUrl, "BackImageUrl");
			g.Caption = "test";
			Assert.AreEqual ("test", g.Caption, "Caption");
			g.CaptionAlign = TableCaptionAlign.Left;
			Assert.AreEqual (TableCaptionAlign.Left, g.CaptionAlign, "CaptionAlign");
			g.CellPadding = 0;
			Assert.AreEqual (0, g.CellPadding, "CellPadding");
			g.CellSpacing = 1;
			Assert.AreEqual (1, g.CellSpacing, "CellSpacing");
			// ToDo: The Columns property default value is tested by the DataControlFieldCollection and DataControlField tests
			string[] str = new String[1];
			str[0] = "test";
			g.DataKeyNames = str;
			Assert.AreEqual ("test", g.DataKeyNames[0], "DataKeyNames");
			
			// ToDo: The DataKeys property default value is tested by the DataKeyArray and DataKey tests
			g.EditIndex = 0;
			Assert.AreEqual (0, g.EditIndex, "EditIndex");
			// The EditRowStyle property default value is tested by the TableItemStyle test (already exists)
			// The EmptyDataRowStyle property default value is tested by the TableItemStyle test (already exists)
			
			MyWebControl.Image myImage = new MyWebControl.Image ();
			myImage.ImageUrl = "myimage.jpg";
			ImageTemplate template = new ImageTemplate ();
			template.MyImage = myImage;
			// end create template image

			g.EmptyDataTemplate = template;
			Assert.IsNotNull (g.EmptyDataTemplate, "EmptyDataTemplate");
			g.EmptyDataText = "test";
			Assert.AreEqual ("test", g.EmptyDataText, "EmptyDataText");

			g.EnableSortingAndPagingCallbacks = true;
			Assert.AreEqual (true, g.EnableSortingAndPagingCallbacks, "EnableSortingAndPagingCallbacks");

			// The FooterStyle property default value is tested by the TableItemStyle test (already exists)
			g.GridLines = GridLines.Horizontal;
			Assert.AreEqual (GridLines.Horizontal, g.GridLines, "GridLines");

			g.HorizontalAlign = HorizontalAlign.Justify;
			Assert.AreEqual (HorizontalAlign.Justify, g.HorizontalAlign, "HorizontalAlign");

			g.PageIndex = 1;
			Assert.AreEqual (1, g.PageIndex, "PageIndex");
			// ToDo: The PagerSettings property default value is tested by the PagerSettings test
			// The PagerStyle property default value is tested by the TableItemStyle test (already exists)
			g.PagerTemplate = template;
			Assert.IsNotNull (g.PagerTemplate, "PagerTemplate");
			g.PageSize = 5;
			Assert.AreEqual (5, g.PageSize, "PageSize");
			g.RowHeaderColumn = "test";
			Assert.AreEqual ("test", g.RowHeaderColumn, "RowHeaderColumn");
			// ToDo: The Rows property default value is tested by the GridViewRowCollection and GridViewRow test			
			// The RowStyle property default value is tested by the TableItemStyle test (already exists)
			g.ShowFooter = true;
			Assert.AreEqual (true, g.ShowFooter, "ShowFooter");
			g.ShowHeader = false;
			Assert.AreEqual (false, g.ShowHeader, "ShowHeader");
			g.UseAccessibleHeader = false;
			Assert.AreEqual (false, g.UseAccessibleHeader, "UseAccessibleHeader");
		}

		[Test]
		public void GridView_DefaultProtectedProperties ()
		{
			PokerGridView g = new PokerGridView ();
			Assert.AreEqual (HtmlTextWriterTag.Table, g.PTagKey, "TagKey");
		}

		[Test]
		public void GridView_Sort_and_DataSourceSelectArguments ()
		{
			DataSourceView view;
			DataSourceSelectArguments arg;
			Page p = new Page ();

			PokerGridView g = new PokerGridView ();
			g.Columns.Add (new BoundField ());
			g.AllowSorting = true;
			p.Controls.Add (g);

			ObjectDataSource data = new ObjectDataSource ();
			data.TypeName = typeof (DataSourceObject).AssemblyQualifiedName;
			data.SelectMethod = "GetList";
			data.SortParameterName = "sortExpression";
			data.ID = "Data";
			p.Controls.Add (data);

			g.DataSourceID = "Data";
			g.EditIndex = 2;
			g.PageIndex = 1;
			g.DataBind ();
			
			g.Sort ("sort", SortDirection.Descending);

			Assert.AreEqual (-1, g.EditIndex, "EditIndex after Sort, Bound by DataSourceID");
			Assert.AreEqual (0, g.PageIndex, "PageIndex after Sort, Bound by DataSourceID");

			arg = g.DoCreateDataSourceSelectArguments();
			view = g.DoGetData ();
			Assert.IsTrue (view.CanSort);
			Assert.AreEqual ("sort", g.SortExpression, "SortExpression, Bound by DataSourceID");
			Assert.AreEqual (SortDirection.Descending, g.SortDirection, "SortDirection, Bound by DataSourceID");
			Assert.AreEqual ("sort DESC", arg.SortExpression, "AllowSorting = true, Bound by DataSourceID");

			g.AllowSorting = false;
			arg = g.DoCreateDataSourceSelectArguments ();
			Assert.AreEqual ("sort DESC", arg.SortExpression, "AllowSorting = false, Bound by DataSourceID");
		}

		[Test]
		public void GridView_PageCount ()
		{
			Page p = new Page ();

			PokerGridView gv = new PokerGridView ();
			gv.PageSize = 3;
			gv.AllowPaging = true;
			p.Controls.Add (gv);

			ObjectDataSource data = new ObjectDataSource ();
			data.ID = "ObjectDataSource1";
			data.TypeName = typeof (DataSourceObject).AssemblyQualifiedName;
			data.SelectMethod = "GetList";
			p.Controls.Add (data);

			gv.DataSourceID = "ObjectDataSource1";
			gv.SetRequiresDataBinding (true);

			Assert.AreEqual (0, gv.PageCount, "PageCount before binding");

			gv.DataBind ();

			Assert.AreEqual (2, gv.PageCount, "PageCount after binding");

			PokerGridView copy = new PokerGridView ();
			copy.LoadState (gv.SaveState ());

			Assert.AreEqual (2, copy.PageCount, "PageCount from ViewState");
		}

		[Test]
		public void GridView_DataKeys ()
		{
			Page p = new Page ();

			PokerGridView gv = new PokerGridView ();
			p.Controls.Add (gv);

			ObjectDataSource data = new ObjectDataSource ();
			data.TypeName = typeof (DataObject).AssemblyQualifiedName;
			data.SelectMethod = "Select";
			p.Controls.Add (data);

			gv.DataSource = data;
			gv.DataKeyNames = new string [] { "ID", "FName" };

			DataKeyArray keys1 = gv.DataKeys;

			Assert.AreEqual (0, keys1.Count, "DataKeys count before binding");

			gv.DataBind ();

			DataKeyArray keys2 = gv.DataKeys;
			DataKeyArray keys3 = gv.DataKeys;

			Assert.IsFalse (Object.ReferenceEquals (keys1, keys2), "DataKey returns the same instans");
			Assert.IsTrue (Object.ReferenceEquals (keys2, keys3), "DataKey returns the same instans");

			Assert.AreEqual (1, keys1.Count, "DataKeys count after binding");
			Assert.AreEqual (1001, keys1 [0].Value, "DataKey.Value after binding");
			Assert.AreEqual (2, keys1 [0].Values.Count, "DataKey.Values count after binding");
			Assert.AreEqual (1001, keys1 [0].Values [0], "DataKey.Values[0] after binding");
			Assert.AreEqual ("Mahesh", keys1 [0].Values [1], "DataKey.Values[1] after binding");

			PokerGridView copy = new PokerGridView ();
			object state = gv.DoSaveControlState ();
			copy.DoLoadControlState (state);

			DataKeyArray keys4 = copy.DataKeys;

			Assert.AreEqual (1, keys4.Count, "DataKeys count from ControlState");
			Assert.AreEqual (1001, keys4 [0].Value, "DataKey.Value from ControlState");
			Assert.AreEqual (2, keys4 [0].Values.Count, "DataKey.Values count from ControlState");
			Assert.AreEqual (1001, keys4 [0].Values [0], "DataKey.Values[0] from ControlState");
			Assert.AreEqual ("Mahesh", keys4 [0].Values [1], "DataKey.Values[1] from ControlState");
		}

		// MSDN: The CreateDataSourceSelectArguments method is a helper method called by 
		// the GridView control to create the DataSourceSelectArguments object that 
		// contains the arguments passed to the data source. In this implementation, 
		// the DataSourceSelectArguments object contains the arguments for paging operations.
		[Test]
		public void GridView_CreateDataSourceSelectArguments ()
		{
			DataSourceView view;
			Page p = new Page ();

			PokerGridView g = new PokerGridView ();
			g.Sorting += new GridViewSortEventHandler (g_Sorting);
			p.Controls.Add (g);

			ObjectDataSource data = new ObjectDataSource ();
			data.TypeName = typeof (DataSourceObject).AssemblyQualifiedName;
			data.SelectMethod = "GetList";
			data.SortParameterName = "sortExpression";
			DataSourceSelectArguments arg;
			p.Controls.Add (data);

			g.DataSource = data;
			g.DataBind ();

			arg = g.DoCreateDataSourceSelectArguments ();
			Assert.IsTrue (arg.Equals (DataSourceSelectArguments.Empty), "Default");

			g.AllowPaging = true;
			g.PageIndex = 2;
			g.PageSize = 3;
			arg = g.DoCreateDataSourceSelectArguments ();
			view = g.DoGetData ();
			Assert.IsFalse (view.CanPage);
			Assert.IsTrue (view.CanRetrieveTotalRowCount);
			Assert.IsTrue (arg.Equals (DataSourceSelectArguments.Empty), "AllowPaging = true, CanPage = false, CanRetrieveTotalRowCount = true");

			// make DataSourceView.CanPage = true
			data.EnablePaging = true;

			arg = g.DoCreateDataSourceSelectArguments ();
			view = g.DoGetData ();
			Assert.IsTrue (view.CanPage);
			Assert.IsFalse (view.CanRetrieveTotalRowCount);
			Assert.IsTrue (arg.Equals (new DataSourceSelectArguments (6, -1)), "AllowPaging = true, CanPage = true, CanRetrieveTotalRowCount = false");

			g.AllowPaging = false;
			arg = g.DoCreateDataSourceSelectArguments ();
			Assert.IsTrue (arg.Equals (DataSourceSelectArguments.Empty), "AllowPaging = false, CanPage = true, CanRetrieveTotalRowCount = false");

			// make DataSourceView.CanRetrieveTotalRowCount = true
			data.SelectCountMethod = "GetCount";

			arg = g.DoCreateDataSourceSelectArguments ();
			Assert.IsTrue (arg.Equals (DataSourceSelectArguments.Empty), "AllowPaging = false, CanPage = true, CanRetrieveTotalRowCount = true");

			g.AllowPaging = true;
			arg = g.DoCreateDataSourceSelectArguments ();
			DataSourceSelectArguments arg1 = new DataSourceSelectArguments (6, 3);
			arg1.RetrieveTotalRowCount = true;
			view = g.DoGetData ();
			Assert.IsTrue (view.CanPage);
			Assert.IsTrue (view.CanRetrieveTotalRowCount);
			Assert.IsTrue (arg.Equals (arg1), "AllowPaging = true, CanPage = true, CanRetrieveTotalRowCount = true");

			g.AllowPaging = false;
			g.AllowSorting = true;
			g.EditIndex = 2;
			g.PageIndex = 1;
			g.Sort ("sort", SortDirection.Descending);

			Assert.AreEqual (2, g.EditIndex, "EditIndex after Sort, Bound by DataSource");
			Assert.AreEqual (1, g.PageIndex, "PageIndex after Sort, Bound by DataSource");
			
			arg = g.DoCreateDataSourceSelectArguments ();
			view = g.DoGetData ();
			Assert.IsTrue (view.CanSort);
			Assert.AreEqual (String.Empty, g.SortExpression, "SortExpression, Bound by DataSource");
			Assert.AreEqual (SortDirection.Ascending, g.SortDirection, "SortDirection, Bound by DataSource");
			Assert.IsTrue (arg.Equals (DataSourceSelectArguments.Empty), "AllowSorting = true, Bound by DataSource");
		}

		static void g_Sorting (object sender, GridViewSortEventArgs e)
		{
			Assert.AreEqual ("sort", e.SortExpression, "GridViewSortEventArgs.SortExpression");
			Assert.AreEqual (SortDirection.Descending, e.SortDirection, "GridViewSortEventArgs.SortDirection");
		}

		[Test]
		public void GridView_DataBind()
		{
			PokerGridView g = new PokerGridView ();
			g.DataSource = myds;
			g.DataBind ();
			Assert.AreEqual (6, g.Rows.Count, "DataBind");

			g.DataSource = null;
			g.DataBind ();
			Assert.AreEqual (0, g.Rows.Count, "DataBind");
		}

		[Test]
		public void GridView_DataBind_NoDataSource ()
		{
			PokerGridView g = new PokerGridView ();
			g.DataBind ();
			Assert.AreEqual (0, g.Rows.Count, "GridView_DataBind_NoDataSource");
		}

		bool rowcreatedchecker;
		bool deleteitemchecker;
		bool sortingaction;

		[Test]
		public void GridView_DeleteItem ()
		{
			PokerGridView g = new PokerGridView ();
			ArrayList myds = new ArrayList ();
			myds.Add ("Norway");
			myds.Add ("Sweden");
			myds.Add ("France");
			myds.Add ("Italy");

			g.DataSource = myds;
			g.DataBind ();
			Assert.AreEqual (false, deleteitemchecker, "DeleteItem#1");
			g.RowDeleting += new GridViewDeleteEventHandler (RowDeletingHandler);
			g.DeleteRow (0);
			Assert.AreEqual (true, deleteitemchecker, "DeleteItem#2");
		}

		protected void RowDeletingHandler (object sender, GridViewDeleteEventArgs e)
		{
			deleteitemchecker = true;
		}

		[Test]
		public void GridView_RowCreated ()
		{
			GridView g = new GridView ();
			ButtonField field = new ButtonField ();
			field.ButtonType = ButtonType.Link;
			field.Text = "Click";
			field.CommandName = "CMD";
			g.Columns.Add (field);
			g.RowCreated += new GridViewRowEventHandler (RowCreatedHandler);

			Assert.AreEqual (false, rowcreatedchecker, "RowCreated#1");

			ArrayList myds = new ArrayList ();
			myds.Add ("Norway");
			myds.Add ("Sweden");
			myds.Add ("France");
			myds.Add ("Italy");

			g.DataSource = myds;
			g.DataBind ();
			Assert.AreEqual (true, rowcreatedchecker, "RowCreated#2");
		}

		protected void RowCreatedHandler (object sender, GridViewRowEventArgs e)
		{
			if (e.Row.Cells.Count > 0)
				rowcreatedchecker = true;

			// Example from MSDN: GridView.RowCreated Event 
 
			// The GridViewCommandEventArgs class does not contain a 
			// property that indicates which row's command button was
			// clicked. To identify which row's button was clicked, use 
			// the button's CommandArgument property by setting it to the 
			// row's index.
			if (e.Row.RowType == DataControlRowType.DataRow) {
				// Retrieve the LinkButton control from the first column.
				IButtonControl addButton = (IButtonControl) e.Row.Cells [0].Controls [0];

				// Set the LinkButton's CommandArgument property with the
				// row's index.
				addButton.CommandArgument = e.Row.RowIndex.ToString ();
			}
		}
		
		[Test]
		public void GridView_Sort ()
		{
			PokerGridView g = new PokerGridView ();
			Assert.AreEqual (false, sortingaction, "BeforeSorting");
			g.Sorting += new GridViewSortEventHandler (Gridview_sorting);
			g.Sort("Item",SortDirection.Descending);
			Assert.AreEqual (true, sortingaction, "AfterSorting");
		}
		
		protected void Gridview_sorting (object sender, GridViewSortEventArgs e)
		{
			sortingaction = true;
		}

		[Test]
		public void GridView_IsBindableType ()
		{
			Type [] types = new Type [] {
				typeof(Boolean), 
				typeof(Byte),
				typeof(Char),
				typeof(DateTime),
				typeof(Decimal),
				typeof(Double),
				typeof(Guid),
				typeof(Int16),
				typeof(Int32),
				typeof(Int64),
				typeof(SByte),
				typeof(Single),
				typeof(String),
				typeof(UInt16),
				typeof(UInt32),
				typeof(UInt64)
				 };

			GridView g = new GridView ();
			foreach (Type type in types)
				Assert.AreEqual (true, g.IsBindableType (type), type.ToString ());

			Assert.AreEqual (false, g.IsBindableType (typeof (Enum)), "test");
			Assert.AreEqual (false, g.IsBindableType (typeof (Object)), "test");
		}

		[Test]
		public void GridView_CreateAutoGeneratedColumn ()
		{
			PokerGridView g = new PokerGridView ();
			AutoGeneratedFieldProperties fp = new AutoGeneratedFieldProperties();
			fp.Name = "testfield";
			fp.Type = typeof (string);
			AutoGeneratedField gf = g.DoCreateAutoGeneratedColumn (fp);
			Assert.AreEqual (typeof (string), gf.DataType , "AutoGeneratedColumn#1");
			Assert.AreEqual ("testfield", gf.HeaderText, "AutoGeneratedColumn#2");
			Assert.AreEqual ("System.Web.UI.WebControls.AutoGeneratedField", gf.GetType ().ToString (), "AutoGeneratedColumn#3");
		}

		[Test]
		public void GridView_CreateChildControls ()
		{
			PokerGridView g = new PokerGridView ();
			g.Page = new Page ();
			g.DataSource = myds;
			g.DataBind ();
			Assert.AreEqual(6,g.DoCreateChildControls(myds,true),"CreateChildControls#1");

			g.AllowPaging = true;
			g.PageSize = 3;
			g.DataBind ();
			Assert.AreEqual (6, g.DoCreateChildControls (myds, true), "CreateChildControls#1");
		}

		class MyEnumSource : IEnumerable
		{
			int _count;

			public MyEnumSource (int count)
			{
				_count = count;
			}

			#region IEnumerable Members

			public IEnumerator GetEnumerator ()
			{
				for (int i = 0; i < _count; i++)
					yield return i;
			}

			#endregion
		}

		[Test]
		public void GridView_CreateChildControls_2 ()
		{
			PokerGridView g = new PokerGridView ();
			g.AutoGenerateColumns = false;
			g.AutoGenerateSelectButton = true;
			g.EmptyDataText = "empty";
			g.Page = new Page ();
			g.DataSource = new MyEnumSource (20);
			//g.DataBind ();
			//Assert.AreEqual (20, g.DoCreateChildControls (new MyEnumSource (20), true), "CreateChildControls#1");
			Assert.AreEqual (0, g.DoCreateChildControls (new MyEnumSource (0), true), "CreateChildControls#2");
		}

		[Test]
		public void GridView_CreateChildControls_1 ()
		{
			PokerGridView g = new PokerGridView ();
			g.AutoGenerateSelectButton = true;
			g.EmptyDataText = "empty";
			Assert.AreEqual (0, g.DoCreateChildControls (new object [0], false), "CreateChildControls#2");
			Assert.AreEqual (-1, g.DoCreateChildControls (new object [5], false), "CreateChildControls#3");
		}

		[Test]
		public void GridView_NullDS ()
		{
			PokerGridView g = new PokerGridView ();
			g.DataSource = null;
			g.DataBind ();
			Assert.AreEqual (0, g.Rows.Count, "NullDS");
		}

		[Test]
		public void GridView_CreateChildTable ()
		{
			PokerGridView g = new PokerGridView ();
			g.ID = "PokerGridView";
			g.Caption = "Caption";
			g.CaptionAlign = TableCaptionAlign.Right;
			g.CellPadding = 2;
			g.CellSpacing = 2;
			Table t = g.DoCreateChildTable ();
			Assert.IsNotNull (t, "CreateChildTable#1");
			Assert.AreEqual (false, t.ControlStyleCreated, "CreateChildTable#2");
		}

		[Test]
		public void GridView_CreateControlStyle ()
		{
			PokerGridView g = new PokerGridView ();
			g.BorderColor = Color.Red;
			g.BorderStyle = BorderStyle.Dashed;
			Style s = g.DoCreateControlStyle ();
			Assert.AreEqual (typeof(TableStyle), s.GetType(), "CreateControlStyle#1");
			Assert.AreEqual (((TableStyle) s).GridLines, GridLines.Both, "CreateControlStyle#2");
			Assert.AreEqual (((TableStyle) s).CellSpacing, 0, "CreateControlStyle#3");
		}

		[Test]
		public void GridView_CreateRow ()
		{
			PokerGridView g = new PokerGridView ();
			GridViewRow gr = g.doCreateRow(0, 0, DataControlRowType.Pager, DataControlRowState.Normal);
			Assert.AreEqual (0, gr.RowIndex, "CreateRow#1");
			Assert.AreEqual (0, gr.DataItemIndex, "CreateRow#2");
			Assert.AreEqual (DataControlRowType.Pager, gr.RowType, "CreateRow#3");
			Assert.AreEqual (DataControlRowState.Normal, gr.RowState, "CreateRow#4");
		}

		[Test]
		public void GridView_GetCallbackResult()
		{
			Page page = new Page ();
			PokerGridView g = new PokerGridView ();
			page.Controls.Add (g);
			string s = g.doGetCallbackResult ();
			if (s == null || s == string.Empty)
				Assert.Fail ("GetCallbackResult");
		}

		[Test]
		public void GridView_InitializePager ()
		{
			PokerGridView gv = new PokerGridView ();
			Page page = new Page ();
			page.Controls.Add (gv);
			gv.AllowPaging = true;
			gv.PageSize = 2;
			gv.DataSource = myds;
			Assert.AreEqual (false, gv.ifPagerInitilized, "BeforeInitializePagerRunned");
			Assert.AreEqual (0, gv.PageCount, "BeforeInitializePagerPageCount");
			gv.DataBind ();
			Assert.AreEqual (true, gv.ifPagerInitilized, "AfterInitializePagerRunned");
			Assert.AreEqual (3, gv.PageCount, "AfterInitializePagerPageCount");
		}

		[Test]
		public void GridView_InitializeRow ()
		{
			// not implemented yet
		}

		[Test]
		public void GridView_ViewState ()
		{
			PokerGridView gv = new PokerGridView ();
			PokerGridView copy = new PokerGridView ();
			gv.AllowPaging = true;
			gv.AllowSorting = true;
			gv.BackColor = Color.Red;
			object state = gv.SaveState ();
			copy.LoadState (state);
			Assert.AreEqual (true, copy.AllowPaging, "ViewStateAllowPaging");
			Assert.AreEqual (true, copy.AllowSorting, "ViewStateAllowSorting");
			Assert.AreEqual (Color.Red, copy.BackColor, "ViewStateBackColor");
		}

		// Private variables for bubble events
		private bool bubbledeleterow;
		private bool bubbleupdaterow;
		private bool bubbleeditingrow;
		private bool bubblesortint;
		private bool bubblecanceling;
		private bool bubbleselect;
		private bool bubblepage;
		private int newPageIndex;

		[Test]
		public void GridView_BubbleEvent ()
		{
			PokerGridView gv = new PokerGridView ();
			Page page = new Page ();
			LinkButton lb = new LinkButton ();
			gv.AllowPaging = true;
			page.Controls.Add (gv);
			gv.DataSource = myds;
			gv.DataBind ();
			gv.EditIndex = 0;
			// 
			gv.RowDeleting += new GridViewDeleteEventHandler (gv_RowDeleting);
			gv.RowUpdating += new GridViewUpdateEventHandler (gv_RowUpdating);
			gv.RowEditing += new GridViewEditEventHandler (gv_RowEditing);
			gv.Sorting += new GridViewSortEventHandler (gv_Sorting);
			gv.RowCancelingEdit += new GridViewCancelEditEventHandler (gv_RowCancelingEdit);
			gv.SelectedIndexChanging+=new GridViewSelectEventHandler(gv_SelectedIndexChanging);
			gv.PageIndexChanging+=new GridViewPageEventHandler(gv_PageIndexChanging);
			// Delete
			GridViewCommandEventArgs com1 = new GridViewCommandEventArgs (lb, new CommandEventArgs ("Delete", "0"));
			Assert.AreEqual (false, bubbledeleterow, "BeforeBubbleEventDeleteRow");
			gv.DoOnBubbleEvent (gv, com1);
			Assert.AreEqual (true, bubbledeleterow, "AfterBubbleEventDeleteRow");
			// Update
			GridViewCommandEventArgs com2 = new GridViewCommandEventArgs (lb, new CommandEventArgs ("Update", "0"));
			Assert.AreEqual (false, bubbleupdaterow, "BeforeBubbleEventUpdateRow");
			gv.DoOnBubbleEvent (gv, com2);
			Assert.AreEqual (true, bubbleupdaterow, "AfterBubbleEventUpdateRow");
			// Edit
			GridViewCommandEventArgs com3 = new GridViewCommandEventArgs (lb, new CommandEventArgs ("Edit", "0"));
			Assert.AreEqual (false, bubbleeditingrow, "BeforeBubbleEventEditingRow");
			gv.DoOnBubbleEvent (gv, com3);
			Assert.AreEqual (true, bubbleeditingrow, "AfterBubbleEventEditingRow");
			// Sort
			gv.AllowSorting = true;
			GridViewCommandEventArgs com4 = new GridViewCommandEventArgs (lb, new CommandEventArgs ("Sort", null));
			Assert.AreEqual (false, bubblesortint, "BeforeBubbleEventSortingRow");
			gv.DoOnBubbleEvent (gv, com4);
			Assert.AreEqual (true, bubblesortint, "AfterBubbleEventSortingRow");
			// Canceling Edit
			GridViewCommandEventArgs com5 = new GridViewCommandEventArgs (lb, new CommandEventArgs ("Cancel", null));
			Assert.AreEqual (false, bubblecanceling, "BeforeBubbleEventcancelingEdit");
			gv.DoOnBubbleEvent (gv, com5);
			Assert.AreEqual (true, bubblecanceling, "AfterBubbleEventcancelingEdit");
			// Select
			GridViewCommandEventArgs com6 = new GridViewCommandEventArgs (gv.SelectedRow, lb, new CommandEventArgs ("Select", "2"));
			Assert.AreEqual (false, bubbleselect, "BeforeBubbleEventSelect");
			gv.DoOnBubbleEvent (gv, com6);
			Assert.AreEqual (true, bubbleselect, "AfterBubbleEventSelect");
			//Next Page
			GridViewCommandEventArgs com7 = new GridViewCommandEventArgs (lb, new CommandEventArgs ("Page", "Next"));
			Assert.AreEqual (false, bubblepage, "BeforeBubbleEventNextPage");
			gv.DoOnBubbleEvent (gv, com7);
			Assert.AreEqual (true, bubblepage, "AfterBubbleEventNextPage");
			Assert.AreEqual (1, newPageIndex, "NextPage");
			// Prev Page
			ResetEvents ();
			GridViewCommandEventArgs com8 = new GridViewCommandEventArgs (lb, new CommandEventArgs ("Page", "Prev"));
			Assert.AreEqual (false, bubblepage, "BeforeBubbleEventPrevPage");
			gv.DoOnBubbleEvent (gv, com8);
			Assert.AreEqual (true, bubblepage, "AfterBubbleEventPrevPage");
			Assert.AreEqual (-1, newPageIndex, "PrevPage");
			ResetEvents ();
			GridViewCommandEventArgs com9 = new GridViewCommandEventArgs (lb, new CommandEventArgs ("Page", "Last"));
			Assert.AreEqual (false, bubblepage, "BeforeBubbleEventLastPage");
			gv.DoOnBubbleEvent (gv, com9);
			Assert.AreEqual (true, bubblepage, "AfterBubbleEventLastPage");
			ResetEvents ();
			GridViewCommandEventArgs com10 = new GridViewCommandEventArgs (lb, new CommandEventArgs ("Page", "First"));
			Assert.AreEqual (false, bubblepage, "BeforeBubbleEventFirstPage");
			gv.DoOnBubbleEvent (gv, com10);
			Assert.AreEqual (true, bubblepage, "AfterBubbleEventFirstPage");
			Assert.AreEqual (0, newPageIndex, "FirstPage");
		}	

		private void gv_RowDeleting (object sender, EventArgs e)
		{
			bubbledeleterow = true;
			rowDeleting = true;
		}

		private void gv_RowUpdating (object sender, EventArgs e)
		{
			bubbleupdaterow = true;
			rowUpdating = true;
		}

		private void gv_RowEditing (object sender, EventArgs e)
		{
			bubbleeditingrow = true;
			rowEditing = true;
		}

		private void gv_Sorting (object sender, EventArgs e)
		{
			bubblesortint = true;
			sorting = true;
		}

		private void gv_RowCancelingEdit (object sender, EventArgs e)
		{
			bubblecanceling = true;
			gridViewCancelEdit = true;
		}

		private void gv_SelectedIndexChanging (object sender, GridViewSelectEventArgs e)
		{
			bubbleselect = true;
			selectIndexChanging = true;
			Assert.AreEqual (2, e.NewSelectedIndex, "SelectedIndexChanging");
		}

		private void gv_PageIndexChanging (object sender, GridViewPageEventArgs e)
		{
			bubblepage = true;
			pageIndexChanging = true;
			newPageIndex = e.NewPageIndex;
			e.NewPageIndex = 0;
		}

		private void ResetEvents ()
		{
			bubblepage = false;
			dataBinding = false;
			pageIndexChanging = false;
			gridViewCancelEdit = false;
			rowDeleting = false;
			rowEditing = false;
			rowUpdating = false;
			selectIndexChanging = false;
			sorting = false;
		}

		// Events variable
		private bool dataBinding;
		private bool dataBound;
		private bool init;
		private bool load;
		private bool pageIndexChanged;
		private bool pageIndexChanging;
		private bool preRender;
		private bool gridViewCancelEdit;
		private bool rowCommand;
		private bool rowCreated;
		private bool rowDataBound;
		private bool rowDeleted;
		private bool rowDeleting;
		private bool rowEditing;
		private bool rowUpdated;
		private bool rowUpdating;
		private bool selectIndexChanged;
		private bool selectIndexChanging;
		private bool sorted;
		private bool sorting;
		private bool unload;

		[Test]
		public void GridView_Events ()
		{
			PokerGridView gv = new PokerGridView ();
			gv.DataSource = myds;

			gv.DataBinding += new EventHandler (gv_DataBinding);
			gv.DataBound += new EventHandler (gv_DataBound);
			gv.PageIndexChanging += new GridViewPageEventHandler (gv_PageIndexChanging);
			gv.PageIndexChanged += new EventHandler (gv_PageIndexChanged);
			gv.PreRender += new EventHandler (gv_PreRender);
			gv.RowCancelingEdit += new GridViewCancelEditEventHandler (gv_RowCancelingEdit);
			gv.RowCommand += new GridViewCommandEventHandler (gv_RowCommand);
			gv.RowCreated += new GridViewRowEventHandler (gv_RowCreated);
			gv.RowDataBound += new GridViewRowEventHandler (gv_RowDataBound);
			gv.RowDeleted += new GridViewDeletedEventHandler(gv_RowDeleted);
			gv.RowDeleting+= new GridViewDeleteEventHandler(gv_RowDeleting);
			gv.RowEditing+=new GridViewEditEventHandler(gv_RowEditing);
			gv.RowUpdated+= new GridViewUpdatedEventHandler(gv_RowUpdated);
			gv.RowUpdating+=new GridViewUpdateEventHandler(gv_RowUpdating);
			gv.SelectedIndexChanged +=new EventHandler(gv_SelectedIndexChanged);
			gv.SelectedIndexChanging+=new GridViewSelectEventHandler(gv_SelectedIndexChanging);
			gv.Sorted +=new EventHandler(gv_Sorted);
			gv.Sorting +=new GridViewSortEventHandler(gv_Sorting);
			gv.Unload+=new EventHandler(gv_Unload);


			Assert.AreEqual (false, dataBinding, "BeforeDataBinding");
			gv.DoOnDataBinding (new EventArgs ());
			Assert.AreEqual (true, dataBinding, "AfterDataBinding");
			Assert.AreEqual (false, dataBound, "BeforeDataBound");
			gv.DoOnDataBound (new EventArgs ());
			Assert.AreEqual (true, dataBound, "AfterDataBound");
			Assert.AreEqual (false, pageIndexChanged, "BeforepageIndexChanged");
			gv.DoOnPageIndexChanged (new EventArgs ());
			Assert.AreEqual (true, pageIndexChanged, "AfterpageIndexChanged");
			ResetEvents ();
			Assert.AreEqual (false, pageIndexChanging, "BeforepageIndexChanging");
			gv.DoOnPageIndexChanging (new GridViewPageEventArgs(1));
			Assert.AreEqual (true, pageIndexChanging, "AfterpageIndexChanging");
			Assert.AreEqual (false, preRender, "BeforePreRender");
			gv.DoOnPreRender (new EventArgs ());
			Assert.AreEqual (true, preRender, "AfterPreRender");
			ResetEvents ();
			Assert.AreEqual (false, gridViewCancelEdit, "BeforeGridViewCancelEdit");
			gv.DoOnRowCancelingEdit (new GridViewCancelEditEventArgs (1));
			Assert.AreEqual (true, gridViewCancelEdit, "AfterGridViewCancelEdit");
			ResetEvents ();
			Assert.AreEqual (false, rowCommand, "BeforeRowCommand");
			LinkButton lb= new LinkButton();
			gv.DoOnRowCommand (new GridViewCommandEventArgs(lb,new CommandEventArgs("",null)));
			Assert.AreEqual (true, rowCommand, "AfterRowCommand");
			Assert.AreEqual (false, rowCreated, "BeforeRowCreated");
			gv.DoOnRowCreated (new GridViewRowEventArgs (gv.SelectedRow));
			Assert.AreEqual (true, rowCommand, "AfterRowCreated");
			Assert.AreEqual (false, rowDataBound, "BeforeRowDataBound");
			gv.DoOnRowDataBound (new GridViewRowEventArgs (gv.SelectedRow)); 
			Assert.AreEqual (true, rowDataBound, "AfterRowDataBound");
			Assert.AreEqual (false, rowDeleted, "BeforeRowDeleted");
			gv.DoOnRowDeleted(new GridViewDeletedEventArgs(1,new ArgumentException()));
			Assert.AreEqual (true, rowDeleted, "AfterRowDeleted");
			ResetEvents ();
			Assert.AreEqual (false, rowDeleting, "BeforeRowDeleting");
			gv.DoOnRowDeleting (new GridViewDeleteEventArgs (0));
			Assert.AreEqual (true, rowDeleting, "AfterRowDeleting");
			ResetEvents ();
			Assert.AreEqual (false, rowEditing, "BeforeRowEditing");
			gv.DoOnRowEditing (new GridViewEditEventArgs (0));
			Assert.AreEqual (true, rowEditing, "AfterRowEditing");
			Assert.AreEqual (false, rowUpdated, "BeforeRowUpdated");
			gv.DoOnRowUpdated (new GridViewUpdatedEventArgs(1,new Exception()));
			Assert.AreEqual (true, rowUpdated, "AfterRowUpdated");
			ResetEvents ();
			Assert.AreEqual (false, rowUpdating, "BeforeRowUpdating");
			gv.DoOnRowUpdating (new GridViewUpdateEventArgs (0));
			Assert.AreEqual (true, rowUpdating, "AfterRowUpdating");
			Assert.AreEqual (false, selectIndexChanged, "BeforeSelectedIndexChanged");
			gv.DoOnSelectedIndexChanged (new EventArgs ());
			Assert.AreEqual (true, selectIndexChanged, "AfterSelectedIndexChanged");
			ResetEvents ();
			Assert.AreEqual (false, selectIndexChanging, "BeforeSelectedIndexChanging");
			gv.DoOnSelectedIndexChanging (new GridViewSelectEventArgs (2));
			Assert.AreEqual (true, selectIndexChanging, "AfterSelectedIndexChanging");
			Assert.AreEqual (false, sorted, "BeforeSorted");
			gv.DoOnSorted (new EventArgs ());
			Assert.AreEqual (true, sorted, "AfterSorted");
			Assert.AreEqual (false, sorting, "BeforeSorting");
			gv.DoOnSorting(new GridViewSortEventArgs("",SortDirection.Ascending));
			Assert.AreEqual (true, sorting, "AfterSorting");
			Assert.AreEqual (false, unload, "BeforeUnload");
			gv.DoOnUnload (new EventArgs ());
			Assert.AreEqual (true, unload, "AfterUnload");

		}

		private void gv_Unload (object sender, EventArgs e)
		{
			unload = true;
		}

		private void gv_Sorted (object sender, EventArgs e)
		{
			sorted = true;
		}

		private void gv_SelectedIndexChanged (object sender, EventArgs e)
		{
			selectIndexChanged = true;
		}

		private void gv_RowUpdated (object sender, EventArgs e)
		{
			rowUpdated = true;
		}

		private void gv_RowDeleted (object sender, EventArgs e)
		{
			rowDeleted = true;
		}

		private void gv_RowDataBound (object sender, EventArgs e)
		{
			rowDataBound = true;
		}

		private void gv_RowCreated (object sender, EventArgs e)
		{
			rowCreated = true;
		}
		 
		private void gv_RowCommand (object sender, EventArgs e)
		{
			rowCommand = true;
		}

		private void gv_PreRender (object sender, EventArgs e)
		{
			preRender = true;
		}

		private void gv_DataBinding (object sender, EventArgs e)
		{
			dataBinding = true;
		}

		private void gv_DataBound (object sender, EventArgs e)
		{
			dataBound = true;
		}

		private void gv_Init (object sender, EventArgs e)
		{
			init = true;
		}

		private void gv_Load (object sender, EventArgs e)
		{
			load = true;
		}

		private void gv_PageIndexChanged (object sender, EventArgs e)
		{
			pageIndexChanged = true;
		}

		[Test]
		[Category ("NunitWeb")]
		public void GridView_DataSourceChangedEvent ()
		{
			WebTest t = new WebTest ();
			PageDelegates pd = new PageDelegates ();
			pd.Load = GridView_Init;
			pd.PreRenderComplete = GridView_Load;
			t.Invoker = new PageInvoker (pd);
			t.Run ();
			FormRequest fr = new FormRequest (t.Response, "form1");
			fr.Controls.Add ("__EVENTTARGET");
			fr.Controls.Add ("__EVENTARGUMENT");
			fr.Controls["__EVENTTARGET"].Value = "";
			fr.Controls["__EVENTARGUMENT"].Value = "";
			t.Request = fr;
			t.Run ();
			if (t.UserData == null)
				Assert.Fail ("DataSourceChangedEvent#1");
			Assert.AreEqual ("Data_rebounded", t.UserData.ToString (), "DataSourceChangedEvent#2");
		}

		#region GridView_DataSourceChangedEvent
		public static void GridView_Init (Page p)
		{
			PokerGridView gv = new PokerGridView ();
			DS data = new DS ();
			p.Controls.Add (gv);
			p.Controls.Add (data);
			data.TypeName = typeof (DS).AssemblyQualifiedName;
			data.SelectMethod = "GetList";
			data.ID = "Data";
			gv.DataBinding += new EventHandler (data_DataBinding);
			gv.DataSourceID = "Data";
		}

		public static void GridView_Load (Page p)
		{
			if (p.IsPostBack) {
				DS data = (DS) p.FindControl ("Data");
				if (data == null)
					Assert.Fail ("Data soource control not created#1");
				data.DoRaiseDataSourceChangedEvent (new EventArgs ());
			}
		}

		public static void data_DataBinding (object sender, EventArgs e)
		{
			if (((WebControl) sender).Page.IsPostBack)
				WebTest.CurrentTest.UserData = "Data_rebounded";
		}
		#endregion

		[Test]
		public void GridView_PerformDataBiding ()
		{
			PokerGridView gv = new PokerGridView ();
			gv.DoPerformDataBinding (myds);
			Assert.AreEqual (6, gv.Rows.Count, "PerformDataBiding_Rows");
		}

		[Test]
		public void GridView_PrepareControlHierarchy ()
		{
			PokerGridView gv = new PokerGridView ();
			gv.controlHierarchy = false;
			gv.Render ();
			Assert.AreEqual (0, gv.Controls.Count, "ControlHierarchy_ControlsCount");
			Assert.AreEqual (true, gv.controlHierarchy, "ControlHierarchy_FirstFlow");
			gv.DataSource = myds;
			gv.DataBind ();
			gv.controlHierarchy = false;
			gv.Render ();
			Assert.AreEqual (1, gv.Controls.Count, "ControlHierarchy_ControlsCountSecondaryFlow");
			Assert.AreEqual (true, gv.controlHierarchy, "ControlHierarchy_SecondaryFlow");
		}

		[Test]
		public void GridView_State ()
		{
			PokerGridView g = new PokerGridView ();
			PokerGridView copy = new PokerGridView ();

			string[] test = new String[1];
			test[0] = "test";
			g.DataKeyNames = test;
			g.EditIndex = 0;
			g.PageIndex = 2;
					
			object state = g.DoSaveControlState ();
			copy.DoLoadControlState (state);

			Assert.AreEqual ("test", copy.DataKeyNames[0], "DataKeyNames");
			Assert.AreEqual (0, copy.EditIndex, "EditIndex");
			Assert.AreEqual (2, copy.PageIndex, "PageIndex");
			
		}

		[Test]
		public void GridView_DefaultsRender ()
		{
			PokerGridView b = new PokerGridView ();
			string html = b.Render ();
			Assert.AreEqual(-1 ,b.Render().IndexOf("table"), "RenderViewState");
		}

		[Test]
		public void GridView_Render ()
		{
			PokerGridView b = new PokerGridView ();
			b.DataSource = myds;
			b.DataBind ();
			string OriginControlHtml = @"<div>
	                                       <table cellspacing=""0"" rules=""all"" border=""1"" style=""border-collapse:collapse;"">
						<tr>
							<th scope=""col"">Item</th>
						</tr><tr>
							<td>Norway</td>
						</tr><tr>
							<td>Sweden</td>
						</tr><tr>
							<td>France</td>
						</tr><tr>
							<td>Italy</td>
						</tr><tr>
							<td>Israel</td>
						</tr><tr>
							<td>Russia</td>
						</tr>
					       </table>
				              </div>";
			string RenderedControlHtml = b.Render ();
			HtmlDiff.AssertAreEqual (OriginControlHtml, RenderedControlHtml, "Rendering");
		}

		[Test]
		public void GridView_RenderAllowPaging ()
		{
			string RenderedPageHtml = new WebTest (PageInvoker.CreateOnLoad (RenderAllowPaging)).Run ();
			string RenderedControlHtml = HtmlDiff.GetControlFromPageHtml (RenderedPageHtml);
			string OriginControlHtml = @"<div>
						     <table cellspacing=""0"" rules=""all"" border=""1"" style=""border-collapse:collapse;"">
		                                     <tr>
			                             <th scope=""col"">Item</th>
						     </tr><tr>
		                                     <td>Norway</td>
		                                     </tr><tr>
			                             <td>Sweden</td>
		                                     </tr><tr>
			                             <td><table border=""0"">
				                     <tr>
					             <td><span>1</span></td><td><a href=""javascript:__doPostBack('ctl01','Page$2')"">2</a></td>
				                     </tr>
			                             </table></td>
		                                     </tr>
	                                             </table>
                                                     </div>";
			HtmlDiff.AssertAreEqual (OriginControlHtml, RenderedControlHtml, "RenderDefault");
		}

		public static void RenderAllowPaging (Page p)
		{
			ArrayList myds = new ArrayList ();
			myds.Add ("Norway");
			myds.Add ("Sweden");
			myds.Add ("France");
			myds.Add ("Italy");
			LiteralControl lcb = new LiteralControl (HtmlDiff.BEGIN_TAG);
			LiteralControl lce = new LiteralControl (HtmlDiff.END_TAG);
			PokerGridView b = new PokerGridView ();
			p.Form.Controls.Add (lcb);
			p.Form.Controls.Add (b);
			b.AllowPaging = true;
			b.PageSize = 2;
			b.DataSource = myds;
			b.DataBind ();
		 	p.Form.Controls.Add (lce);
		}

		[Test]
		[Category("NunitWeb")]
		public void GridView_RenderAllowPaging2 ()
		{
			string RenderedPageHtml = new WebTest (PageInvoker.CreateOnLoad (RenderAllowPaging2)).Run ();
			string RenderedControlHtml = HtmlDiff.GetControlFromPageHtml (RenderedPageHtml);
			string OriginControlHtml = @"<div>
										<table cellspacing=""0"" rules=""all"" border=""1"" style=""border-collapse:collapse;"">
											<tr>
												<th scope=""col"">Item</th>
											</tr><tr>
												<td>France</td>
											</tr><tr>
												<td>Italy</td>
											</tr><tr>
												<td><table border=""0"">
													<tr>
														<td><a href=""javascript:__doPostBack('ctl01','Page$1')"">1</a></td><td><span>2</span></td><td><a href=""javascript:__doPostBack('ctl01','Page$3')"">3</a></td><td><a href=""javascript:__doPostBack('ctl01','Page$4')"">4</a></td><td><a href=""javascript:__doPostBack('ctl01','Page$5')"">...</a></td><td><a href=""javascript:__doPostBack('ctl01','Page$Last')"">&gt;&gt;</a></td>
													</tr>
												</table></td>
											</tr>
										</table>
									</div>";
			HtmlDiff.AssertAreEqual (OriginControlHtml, RenderedControlHtml, "RenderDefault");
		}

		public static void RenderAllowPaging2 (Page p)
		{
			ArrayList myds = new ArrayList ();
			myds.Add ("Norway");
			myds.Add ("Sweden");
			myds.Add ("France");
			myds.Add ("Italy");
			myds.Add ("Norway");
			myds.Add ("Sweden");
			myds.Add ("France");
			myds.Add ("Italy");
			myds.Add ("Norway");
			myds.Add ("Sweden");
			myds.Add ("France");
			myds.Add ("Italy");
			LiteralControl lcb = new LiteralControl (HtmlDiff.BEGIN_TAG);
			LiteralControl lce = new LiteralControl (HtmlDiff.END_TAG);
			PokerGridView b = new PokerGridView ();
			p.Form.Controls.Add (lcb);
			p.Form.Controls.Add (b);
			b.AllowPaging = true;
			b.PageSize = 2;
			b.PageIndex = 1;
			b.PagerSettings.PageButtonCount = 4;
			b.PagerSettings.Mode= PagerButtons.NumericFirstLast;
			b.DataSource = myds;
			b.DataBind ();
			p.Form.Controls.Add (lce);
		}

		[Test]
		public void GridView_RenderProperty ()
		{
			string RenderedPageHtml = new WebTest (PageInvoker.CreateOnLoad (RenderProperty)).Run ();
			string RenderedControlHtml = HtmlDiff.GetControlFromPageHtml (RenderedPageHtml);
			string OriginControlHtml = @"<div id=""__gvctl01__div"">
							<table cellspacing=""1"" cellpadding=""0"" align=""Justify"" rules=""rows"" border=""1"" style=""background-image:url(http://test);"">
								<caption align=""Left"">
									test
								</caption><tr>
									<td><a href=""javascript:__doPostBack('ctl01','Edit$0')"">Edit</a>&nbsp;<a href=""javascript:__doPostBack('ctl01','Delete$0')"">Delete</a></td><td>Norway</td>
								</tr><tr>
									<td><a href=""javascript:__doPostBack('ctl01','Edit$1')"">Edit</a>&nbsp;<a href=""javascript:__doPostBack('ctl01','Delete$1')"">Delete</a></td><td>Sweden</td>
								</tr><tr>
									<td><a href=""javascript:__doPostBack('ctl01','Edit$2')"">Edit</a>&nbsp;<a href=""javascript:__doPostBack('ctl01','Delete$2')"">Delete</a></td><td>France</td>
								</tr><tr>
									<td><a href=""javascript:__doPostBack('ctl01','Edit$3')"">Edit</a>&nbsp;<a href=""javascript:__doPostBack('ctl01','Delete$3')"">Delete</a></td><td>Italy</td>
								</tr><tr>
									<td>&nbsp;</td><td>&nbsp;</td>
								</tr>
							</table>
						</div>";
			HtmlDiff.AssertAreEqual (OriginControlHtml, RenderedControlHtml, "RenderDefault");
		}

		public static void RenderProperty (Page p)
		{
			// Array list for simple datasource
			ArrayList myds = new ArrayList ();
			myds.Add ("Norway");
			myds.Add ("Sweden");
			myds.Add ("France");
			myds.Add ("Italy");
			
			// Helper controls for searching usefull data from page 
			LiteralControl lcb = new LiteralControl (HtmlDiff.BEGIN_TAG);
			LiteralControl lce = new LiteralControl (HtmlDiff.END_TAG);
			PokerGridView g = new PokerGridView ();
			
			// Changing some property for test
			g.AutoGenerateDeleteButton = true;
			g.AutoGenerateEditButton = true;
			g.BackImageUrl = "http://test";
			g.Caption = "test";
			g.CaptionAlign = TableCaptionAlign.Left;
			g.CellPadding = 0;
			g.CellSpacing = 1;
			g.EnableSortingAndPagingCallbacks = true;
			g.GridLines = GridLines.Horizontal;
			g.HorizontalAlign = HorizontalAlign.Justify;
			g.ShowFooter = true;
			g.ShowHeader = false;
			g.UseAccessibleHeader = false;
			
			// Add controls for page
			p.Form.Controls.Add (lcb);
			p.Form.Controls.Add (g);
			
			// Data source and bind
			g.DataSource = myds;
			g.DataBind ();
			p.Form.Controls.Add (lce);
		}

		/// <summary>
		/// From here rendering all possible field types and kinds of 
		/// templates 
		/// </summary>

		[Test]
		public void GridView_RenderingBoundField ()
		{
			string RenderedPageHtml = new WebTest (PageInvoker.CreateOnLoad (RenderingBoundField)).Run ();
			string RenderedControlHtml = HtmlDiff.GetControlFromPageHtml (RenderedPageHtml);
			string OriginControlHtml = @"<div>
							<table cellspacing=""0"" rules=""all"" border=""1"" style=""border-collapse:collapse;"">
								<tr>
									<th scope=""col"">HeaderText</th>
								</tr><tr>
									<td>1</td>
								</tr><tr>
									<td>2</td>
								</tr><tr>
									<td>FooterText</td>
								</tr>
							</table>
						    </div>";
			HtmlDiff.AssertAreEqual (OriginControlHtml, RenderedControlHtml, "RenderingBoundField");
		}

		[Test]
		public void GridView_RenderingCheckBoxField ()
		{
			string RenderedPageHtml = new WebTest (PageInvoker.CreateOnLoad (RenderingCheckBoxField)).Run ();
			string RenderedControlHtml = HtmlDiff.GetControlFromPageHtml (RenderedPageHtml);
			string OriginControlHtml = @"<div>
							<table cellspacing=""0"" rules=""all"" border=""1"" style=""border-collapse:collapse;"">
							<tr>
								<th scope=""col"">HeaderText</th>
							</tr><tr>
								<td><span disabled=""disabled""><input id="""" type=""checkbox"" name="""" checked=""checked"" disabled=""disabled"" /></span></td>
							</tr><tr>
								<td><span disabled=""disabled""><input id="""" type=""checkbox"" name="""" disabled=""disabled"" /></span></td>
							</tr><tr>
								<td>FooterText</td>
							</tr>
							</table>
							</div>";
			HtmlDiff.AssertAreEqual (OriginControlHtml, RenderedControlHtml, "RenderingCheckBoxField");
		}

		[Test]
		public void GridView_RenderingCheckBoxField2 ()
		{
			string RenderedPageHtml = new WebTest (PageInvoker.CreateOnLoad (RenderingCheckBoxField2)).Run ();
			string RenderedControlHtml = HtmlDiff.GetControlFromPageHtml (RenderedPageHtml);
			string OriginControlHtml = @"<div>
											<table cellspacing=""0"" rules=""all"" border=""1"" style=""border-collapse:collapse;"">
												<tr>
													<th scope=""col"">bool</th><th scope=""col"">str</th>
												</tr><tr>
													<td><span disabled=""disabled"" title=""bool""><input id=""ctl01_ctl02_ctl00"" type=""checkbox"" name=""ctl01$ctl02$ctl00"" checked=""checked"" disabled=""disabled"" /></span></td><td>1</td>
												</tr><tr>
													<td><span disabled=""disabled"" title=""bool""><input id=""ctl01_ctl03_ctl00"" type=""checkbox"" name=""ctl01$ctl03$ctl00"" disabled=""disabled"" /></span></td><td>2</td>
												</tr><tr>
													<td>&nbsp;</td><td>&nbsp;</td>
												</tr>
											</table>
										</div>";
			HtmlDiff.AssertAreEqual (OriginControlHtml, RenderedControlHtml, "RenderingCheckBoxField2");
		}
		
		[Test]
		public void GridView_RenderingImageField ()
		{
			string RenderedPageHtml = new WebTest (PageInvoker.CreateOnLoad (RenderingImageField)).Run ();
			string RenderedControlHtml = HtmlDiff.GetControlFromPageHtml (RenderedPageHtml);
			string OriginControlHtml = @"<div>
							<table cellspacing=""0"" rules=""all"" border=""1"" style=""border-collapse:collapse;"">
								<tr>
									<th scope=""col"">HeaderText</th>
								</tr><tr>
									<td><img src=""1"" alt=""1"" style=""border-width:0px;"" /></td>
								</tr><tr>
									<td><img src=""2"" alt=""2"" style=""border-width:0px;"" /></td>
								</tr><tr>
									<td>FooterText</td>
								</tr>
							</table>
						</div>";
			HtmlDiff.AssertAreEqual (OriginControlHtml, RenderedControlHtml, "RenderingImageField");
		}

		[Test]
		public void GridView_RenderingCommandField ()
		{
			string RenderedPageHtml = new WebTest (PageInvoker.CreateOnLoad (RenderingCommandField)).Run ();
			string RenderedControlHtml = HtmlDiff.GetControlFromPageHtml (RenderedPageHtml);
			string OriginControlHtml = @"<div>
							<table cellspacing=""0"" rules=""all"" border=""1"" style=""border-collapse:collapse;"">
								<tr>
									<th scope=""col"">HeaderText</th>
								</tr><tr>
									<td><a href=""javascript:__doPostBack('ctl01','Edit$0')"">Edit</a>&nbsp;<a href=""javascript:__doPostBack('ctl01','Delete$0')"">Delete</a>&nbsp;<a href=""javascript:__doPostBack('ctl01','New$0')"">New</a>&nbsp;<a href=""javascript:__doPostBack('ctl01','Select$0')"">Select</a></td>
								</tr><tr>
									<td><a href=""javascript:__doPostBack('ctl01','Edit$1')"">Edit</a>&nbsp;<a href=""javascript:__doPostBack('ctl01','Delete$1')"">Delete</a>&nbsp;<a href=""javascript:__doPostBack('ctl01','New$1')"">New</a>&nbsp;<a href=""javascript:__doPostBack('ctl01','Select$1')"">Select</a></td>
								</tr><tr>
									<td>FooterText</td>
								</tr>
							</table>
						     </div>";
			HtmlDiff.AssertAreEqual (OriginControlHtml, RenderedControlHtml, "RenderingCommandField");
		}

		[Test]
		public void GridView_RenderingHyperLinkField ()
		{
			string RenderedPageHtml = new WebTest (PageInvoker.CreateOnLoad (RenderingHyperLinkField)).Run ();
			string RenderedControlHtml = HtmlDiff.GetControlFromPageHtml (RenderedPageHtml);
			string OriginControlHtml = @"<div>
							<table cellspacing=""0"" rules=""all"" border=""1"" style=""border-collapse:collapse;"">
								<tr>
									<th scope=""col"">HeaderText</th>
								</tr><tr>
									<td><a href=""1"">1</a></td>
								</tr><tr>
									<td><a href=""2"">2</a></td>
								</tr><tr>
									<td>FooterText</td>
								</tr>
							</table>
						</div>";
			HtmlDiff.AssertAreEqual (OriginControlHtml, RenderedControlHtml, "RenderingHyperLinkField");
		}

		[Test]
		public void GridView_RenderingButtonField ()
		{
			string RenderedPageHtml = new WebTest (PageInvoker.CreateOnLoad (RenderingButtonField)).Run ();
			string RenderedControlHtml = HtmlDiff.GetControlFromPageHtml (RenderedPageHtml);
			string OriginControlHtml = @"<div>
							<table cellspacing=""0"" rules=""all"" border=""1"" style=""border-collapse:collapse;"">
								<tr>
									<th scope=""col"">HeaderText</th><th scope=""col"">HeaderText</th><th scope=""col"">HeaderText</th>
								</tr><tr>
									<td><input type=""button"" value=""1"" onclick=""javascript:__doPostBack('ctl01','0')"" /></td><td><a href=""javascript:__doPostBack('ctl01','0')"">1</a></td><td><input type=""image"" src="""" alt=""1"" onclick=""javascript:__doPostBack('ctl01','0')"" style=""border-width:0px;"" /></td>
								</tr><tr>
									<td><input type=""button"" value=""2"" onclick=""javascript:__doPostBack('ctl01','1')"" /></td><td><a href=""javascript:__doPostBack('ctl01','1')"">2</a></td><td><input type=""image"" src="""" alt=""2"" onclick=""javascript:__doPostBack('ctl01','1')"" style=""border-width:0px;"" /></td>
								</tr><tr>
									<td>FooterText</td><td>FooterText</td><td>FooterText</td>
								</tr>
							</table>
						</div>";
			HtmlDiff.AssertAreEqual (OriginControlHtml, RenderedControlHtml, "RenderingButtonField");
		}

		[Test (Description="Bug #551666")]
		public void TableSections_Bug551666 ()
		{
			string html = new WebTest ("TableSections_Bug551666.aspx").Run ();
			string renderedHtml = HtmlDiff.GetControlFromPageHtml (html);
			string originalHtml = @"<div>
	<table id=""GridView1"" cellspacing=""0"" rules=""all"" border=""1"" style=""border-collapse:collapse;"">
			<thead>
				<tr>
					<th scope=""col"">Dosage</th><th scope=""col"">Drug</th><th scope=""col"">Patient</th><th scope=""col"">Date</th>
				</tr>
			</thead><tbody>

				<tr>
					<td>25</td><td>Indocin</td><td>David</td><td>2009-11-13</td>
				</tr><tr>
					<td>50</td><td>Enebrel</td><td>Sam</td><td>2009-11-13</td>
				</tr><tr>

					<td>10</td><td>Hydralazine</td><td>Christoff</td><td>2009-11-13</td>
				</tr><tr>
					<td>21</td><td>Combivent</td><td>Janet</td><td>2009-11-13</td>
				</tr><tr>
					<td>100</td><td>Dilantin</td><td>Melanie</td><td>2009-11-13</td>

				</tr>
			</tbody><tfoot>

			</tfoot>
		</table>
	</div>";
			
			HtmlDiff.AssertAreEqual (originalHtml, renderedHtml, "#A1");
		}
		
		[Test]
		public void GridView_RenderingTemplateField ()
		{
		        
			string RenderedPageHtml = new WebTest (PageInvoker.CreateOnLoad (RenderingTemplateField)).Run ();
			string RenderedControlHtml = HtmlDiff.GetControlFromPageHtml (RenderedPageHtml);
			string OriginControlHtml = @"<div>
							<table cellspacing=""0"" rules=""all"" border=""1"" style=""border-collapse:collapse;"">
								<tr>
									<th scope=""col""><input name="""" type=""text"" id="""" /></th>
								</tr><tr>
									<td><input name="""" type=""text"" value=""1"" id="""" /></td>
								</tr><tr>
									<td><input name="""" type=""text"" value=""2"" id="""" /></td>
								</tr><tr>
									<td><input name="""" type=""text"" id="""" /></td>
								</tr>
							</table>
						      </div>";
			HtmlDiff.AssertAreEqual (OriginControlHtml, RenderedControlHtml, "RenderingTemplateField");
		}

		
		public static void RenderingTemplateField (Page p)
		{
			LiteralControl lcb = new LiteralControl (HtmlDiff.BEGIN_TAG);
			LiteralControl lce = new LiteralControl (HtmlDiff.END_TAG);
			GridView grid = new GridView ();
			grid.ID = "grid";
			grid.AutoGenerateColumns = false;
			grid.ShowFooter = true;
			TemplateField templatefield = new TemplateField ();
			templatefield.InsertVisible = true;
			templatefield.Visible = true;
			templatefield.HeaderText = "HeaderText";
			templatefield.FooterText = "FooterText";
			templatefield.ItemTemplate = new CompiledTemplateBuilder(BuildControl_itemtemplate);
			templatefield.HeaderTemplate = new CompiledTemplateBuilder (BuildControl_itemtemplate);
			templatefield.FooterTemplate= new CompiledTemplateBuilder (BuildControl_itemtemplate);
			grid.DataSource = GridViewTest.CreateDataSource ();
			grid.Columns.Add (templatefield);
			p.Form.Controls.Add (lcb);
			p.Form.Controls.Add (grid);
			p.Form.Controls.Add (lce);
			grid.DataBind ();
		}

		private static void BuildControl_itemtemplate (Control container)
		{
			TextBox ctrl;
			ctrl = new TextBox ();
			ctrl.ID = "TextBox1";
			ctrl.DataBinding += MyDataBinding;
			container.Controls.Add (ctrl);
		}

		private static void MyDataBinding (object sender, EventArgs e)
		{
			TextBox Target;
			IDataItemContainer Container;
			Target = (TextBox) sender;
			Container = (IDataItemContainer) Target.BindingContainer;
			if ((Target.Page.GetDataItem () != null))
				Target.Text = Convert.ToString (DataBinder.Eval (Target.Page.GetDataItem(),"str"));
		}


		public static void RenderingButtonField (Page p)
		{
			LiteralControl lcb = new LiteralControl (HtmlDiff.BEGIN_TAG);
			LiteralControl lce = new LiteralControl (HtmlDiff.END_TAG);
			GridView grid = new GridView ();
			grid.AutoGenerateColumns = false;
			grid.ShowFooter = true;
			p.Form.Controls.Add (lcb);
			p.Form.Controls.Add (grid);
			p.Form.Controls.Add (lce);

			ButtonField buttonfield = new ButtonField ();
			buttonfield.HeaderText = "HeaderText";
			buttonfield.FooterText = "FooterText";
			buttonfield.ButtonType = ButtonType.Button;
			buttonfield.DataTextField = STRINGFIELD;

			ButtonField buttonfieldlink = new ButtonField ();
			buttonfieldlink.HeaderText = "HeaderText";
			buttonfieldlink.FooterText = "FooterText";
			buttonfieldlink.ButtonType = ButtonType.Link;
			buttonfieldlink.DataTextField = STRINGFIELD;
			buttonfieldlink.CommandName = "cmd2";

			ButtonField buttonfieldimage = new ButtonField ();
			buttonfieldimage.HeaderText = "HeaderText";
			buttonfieldimage.FooterText = "FooterText";
			buttonfieldimage.ButtonType = ButtonType.Image;
			buttonfieldimage.DataTextField = STRINGFIELD;
			buttonfieldimage.CommandName = "cmd3";

			grid.DataSource = GridViewTest.CreateDataSource ();
			grid.Columns.Add (buttonfield);
			grid.Columns.Add (buttonfieldlink);
			grid.Columns.Add (buttonfieldimage);
			grid.DataBind ();
		}

		public static void RenderingHyperLinkField (Page p)
		{
			LiteralControl lcb = new LiteralControl (HtmlDiff.BEGIN_TAG);
			LiteralControl lce = new LiteralControl (HtmlDiff.END_TAG);
			GridView grid = new GridView ();
			grid.AutoGenerateColumns = false;
			grid.ShowFooter = true;
			p.Form.Controls.Add (lcb);
			p.Form.Controls.Add (grid);
			p.Form.Controls.Add (lce);
			HyperLinkField hyperlinkfield = new HyperLinkField ();
			hyperlinkfield.DataTextField = STRINGFIELD;
			string[] str = new string[] { STRINGFIELD };
			hyperlinkfield.DataNavigateUrlFields = str;
			hyperlinkfield.HeaderText = "HeaderText";
			hyperlinkfield.FooterText = "FooterText";
			grid.DataSource = GridViewTest.CreateDataSource ();
			grid.Columns.Add (hyperlinkfield);
			grid.DataBind ();
		}

		public static void RenderingCommandField (Page p)
		{
			LiteralControl lcb = new LiteralControl (HtmlDiff.BEGIN_TAG);
			LiteralControl lce = new LiteralControl (HtmlDiff.END_TAG);
			GridView grid = new GridView ();
			grid.AutoGenerateColumns = false;
			grid.ShowFooter = true;
			p.Form.Controls.Add (lcb);
			p.Form.Controls.Add (grid);
			p.Form.Controls.Add (lce);
			CommandField commandfield = new CommandField ();
			commandfield.HeaderText = "HeaderText";
			commandfield.FooterText = "FooterText";
			commandfield.ShowCancelButton = true;
			commandfield.ShowDeleteButton = true;
			commandfield.ShowEditButton = true;
			commandfield.ShowInsertButton = true;
			commandfield.ShowSelectButton = true;
			grid.DataSource = GridViewTest.CreateDataSource ();
			grid.Columns.Add (commandfield);
			grid.DataBind ();
		}

		public static void RenderingImageField (Page p)
		{
			LiteralControl lcb = new LiteralControl (HtmlDiff.BEGIN_TAG);
			LiteralControl lce = new LiteralControl (HtmlDiff.END_TAG);
			GridView grid = new GridView ();
			grid.AutoGenerateColumns = false;
			grid.ShowFooter = true;
			p.Form.Controls.Add (lcb);
			p.Form.Controls.Add (grid);
			p.Form.Controls.Add (lce);
			ImageField imagefield = new ImageField ();
			imagefield.HeaderText = "HeaderText";
			imagefield.FooterText = "FooterText";
			imagefield.DataImageUrlField = STRINGFIELD;
			imagefield.DataAlternateTextField = STRINGFIELD;
			grid.DataSource = GridViewTest.CreateDataSource ();
			grid.Columns.Add (imagefield);
			grid.DataBind ();
		}

		public static void RenderingBoundField (Page p)
		{
			LiteralControl lcb = new LiteralControl (HtmlDiff.BEGIN_TAG);
			LiteralControl lce = new LiteralControl (HtmlDiff.END_TAG);
			GridView grid = new GridView ();
			grid.AutoGenerateColumns = false;
			grid.ShowFooter = true;
			p.Form.Controls.Add (lcb);
			p.Form.Controls.Add (grid);
			p.Form.Controls.Add (lce);
			BoundField boundfield = new BoundField ();
			boundfield.DataField = STRINGFIELD;
			boundfield.HeaderText = "HeaderText";
			boundfield.FooterText = "FooterText";
			grid.DataSource = GridViewTest.CreateDataSource ();
			grid.Columns.Add (boundfield);
			grid.DataBind ();
		}

		public static void RenderingCheckBoxField (Page p)
		{
			LiteralControl lcb = new LiteralControl (HtmlDiff.BEGIN_TAG);
			LiteralControl lce = new LiteralControl (HtmlDiff.END_TAG);
			GridView grid = new GridView ();
			grid.AutoGenerateColumns = false;
			grid.ShowFooter = true;
			CheckBoxField checkboxfield = new CheckBoxField ();
			checkboxfield.DataField = BOOLFIELD;
			checkboxfield.HeaderText = "HeaderText";
			checkboxfield.FooterText = "FooterText";
			p.Form.Controls.Add (lcb);
			p.Form.Controls.Add (grid);
			p.Form.Controls.Add (lce);
			grid.DataSource = GridViewTest.CreateDataSource ();
			grid.Columns.Add (checkboxfield);
			grid.DataBind ();
		}

		public static void RenderingCheckBoxField2 (Page p)
		{
			LiteralControl lcb = new LiteralControl (HtmlDiff.BEGIN_TAG);
			LiteralControl lce = new LiteralControl (HtmlDiff.END_TAG);
			GridView grid = new GridView ();
			grid.AutoGenerateColumns = true;
			grid.ShowFooter = true;
			p.Form.Controls.Add (lcb);
			p.Form.Controls.Add (grid);
			p.Form.Controls.Add (lce);
			grid.DataSource = GridViewTest.CreateDataSource ();
			grid.DataBind ();
		}
		///////////////////////////////////////////////////////
		/////		   GRIDVIEW   POSTBACK           //////
		///////////////////////////////////////////////////////

		[Test]
		public void GridView_GetPostBackOptions ()
		{
			GridView gv = new GridView ();
			gv.Page = new Page ();
			IButtonControl btn = new Button ();
			btn.CausesValidation = false;
			Assert.IsFalse (btn.CausesValidation);
			Assert.AreEqual (String.Empty, btn.CommandName);
			Assert.AreEqual (String.Empty, btn.CommandArgument);
			Assert.AreEqual (String.Empty, btn.PostBackUrl);
			Assert.AreEqual (String.Empty, btn.ValidationGroup);
			PostBackOptions options = ((IPostBackContainer) gv).GetPostBackOptions (btn);
			Assert.IsFalse (options.PerformValidation);
			Assert.IsFalse (options.AutoPostBack);
			Assert.IsFalse (options.TrackFocus);
			Assert.IsTrue (options.ClientSubmit);
			Assert.IsTrue (options.RequiresJavaScriptProtocol);
			Assert.AreEqual ("$", options.Argument);
			Assert.AreEqual (null, options.ActionUrl);
			Assert.AreEqual (null, options.ValidationGroup);

			btn.ValidationGroup = "VG";
			btn.CommandName = "CMD";
			btn.CommandArgument = "ARG";
			btn.PostBackUrl = "Page.aspx";
			Assert.IsFalse (btn.CausesValidation);
			Assert.AreEqual ("CMD", btn.CommandName);
			Assert.AreEqual ("ARG", btn.CommandArgument);
			Assert.AreEqual ("Page.aspx", btn.PostBackUrl);
			Assert.AreEqual ("VG", btn.ValidationGroup);
			options = ((IPostBackContainer) gv).GetPostBackOptions (btn);
			Assert.IsFalse (options.PerformValidation);
			Assert.IsFalse (options.AutoPostBack);
			Assert.IsFalse (options.TrackFocus);
			Assert.IsTrue (options.ClientSubmit);
			Assert.IsTrue (options.RequiresJavaScriptProtocol);
			Assert.AreEqual ("CMD$ARG", options.Argument);
			Assert.AreEqual (null, options.ActionUrl);
			Assert.AreEqual (null, options.ValidationGroup);
		}

		[Test]
		[ExpectedException (typeof (InvalidOperationException))]
		public void GridView_GetPostBackOptions_CausesValidation ()
		{
			GridView gv = new GridView ();
			gv.Page = new Page ();
			IButtonControl btn = new Button ();
			Assert.IsTrue (btn.CausesValidation);
			Assert.AreEqual (String.Empty, btn.CommandName);
			Assert.AreEqual (String.Empty, btn.CommandArgument);
			Assert.AreEqual (String.Empty, btn.PostBackUrl);
			Assert.AreEqual (String.Empty, btn.ValidationGroup);
			PostBackOptions options = ((IPostBackContainer) gv).GetPostBackOptions (btn);
		}
		
		[Test]
		[ExpectedException(typeof(ArgumentNullException))]
		public void GridView_GetPostBackOptions_Null_Argument ()
		{
			GridView gv = new GridView ();
			gv.Page = new Page ();
			PostBackOptions options = ((IPostBackContainer) gv).GetPostBackOptions (null);
		}

		[Test]
		[Category ("NunitWeb")]
		public void GridView_PostBackSotring ()
		{
			WebTest t = new WebTest (PageInvoker.CreateOnLoad (GridView_postback));
			string pageHTML = t.Run ();
			Assert.AreEqual (-1, pageHTML.IndexOf ("SortingSuccess"), "BeforeSorting");
			FormRequest fr = new FormRequest (t.Response, "form1");
			fr.Controls.Add ("__EVENTTARGET");
			fr.Controls.Add ("__EVENTARGUMENT");
			fr.Controls["__EVENTTARGET"].Value = "mygrid";
			fr.Controls["__EVENTARGUMENT"].Value = "Sort$Item";
			t.Request = fr;
			t.Invoker = PageInvoker.CreateOnLoad (GridView_postback);
			pageHTML = t.Run ();
			if (pageHTML.IndexOf ("SortingSuccess") < 0)
				Assert.Fail ("SortingFail");
		}

		[Test]
		[Category ("NunitWeb")]
		public void GridView_PostBackPaging ()
		{
			WebTest t = new WebTest (PageInvoker.CreateOnLoad (GridView_postback));
			string pageHTML = t.Run ();
			Assert.AreEqual (-1, pageHTML.IndexOf ("PagingSuccess"), "BeforePaging");
			FormRequest fr = new FormRequest (t.Response, "form1");
			fr.Controls.Add ("__EVENTTARGET");
			fr.Controls.Add ("__EVENTARGUMENT");
			fr.Controls["__EVENTTARGET"].Value = "mygrid";
			fr.Controls["__EVENTARGUMENT"].Value = "Page$2";
			t.Request = fr;
			t.Invoker = PageInvoker.CreateOnLoad (GridView_postback);
			pageHTML = t.Run ();
			if (pageHTML.IndexOf ("PagingSuccess") < 0)
				Assert.Fail ("PagingFail");
		}

		[Test]
		[Category ("NunitWeb")]
		public void GridView_PostBackDelete ()
		{
			WebTest t = new WebTest (PageInvoker.CreateOnLoad (GridView_postback));
			string pageHTML = t.Run ();
			Assert.AreEqual (-1, pageHTML.IndexOf ("DeleteSuccess"), "BeforeDelete");
			FormRequest fr = new FormRequest (t.Response, "form1");
			fr.Controls.Add ("__EVENTTARGET");
			fr.Controls.Add ("__EVENTARGUMENT");
			fr.Controls["__EVENTTARGET"].Value = "mygrid";
			fr.Controls["__EVENTARGUMENT"].Value = "Delete$0";
			t.Request = fr;
			t.Invoker = PageInvoker.CreateOnLoad (GridView_postback);
			pageHTML = t.Run ();
			if (pageHTML.IndexOf ("DeleteSuccess") < 0)
				Assert.Fail ("DeleteFail");
		}

		[Test]
		[Category ("NunitWeb")]
		public void GridView_PostBackDeleteItem ()
		{
			WebTest t = new WebTest ();
			PageDelegates pd = new PageDelegates ();
			pd.Load = GridView_postbackdeleteitem;
			pd.PreRenderComplete = GridView_checkrows;
			t.Invoker = new PageInvoker (pd);
			string pageHTML = t.Run ();
			if (pageHTML.IndexOf ("Delete") < 0){
				Assert.Fail ("BeforeDelete");
			}
			Assert.AreEqual (1, t.UserData , "ObjectDataSource before delete from grid"); 
			FormRequest fr = new FormRequest (t.Response, "form1");
			fr.Controls.Add ("__EVENTTARGET");
			fr.Controls.Add ("__EVENTARGUMENT");
			fr.Controls["__EVENTTARGET"].Value = "Grid";
			fr.Controls["__EVENTARGUMENT"].Value = "Delete$0";
			t.Request = fr;
			pageHTML = t.Run ();
			Assert.AreEqual (0, t.UserData , "ObjectDataSource after delete from grid");
		}

		public static void GridView_checkrows (Page p)
		{
			GridView grid = p.FindControl ("Grid") as GridView;
			if (grid == null)
				Assert.Fail ("GridView does not created");

			WebTest.CurrentTest.UserData = grid.Rows.Count;
		}

		public static void GridView_postbackdeleteitem (Page p)
		{
			GridView grid = new GridView ();
			ObjectDataSource ds = new ObjectDataSource ();
			ds.ID = "ObjectDataSource2";

			ds.TypeName = "MonoTests.System.Web.UI.WebControls.DataObject";
			ds.SelectMethod = "Select";
			ds.DeleteMethod = "Delete";
			ds.InsertMethod = "Insert";
			ds.UpdateMethod = "Update";
			Parameter p1 = new Parameter ("ID", TypeCode.String);
			Parameter p2 = new Parameter ("FName", TypeCode.String);
			Parameter p3 = new Parameter ("LName", TypeCode.String);
			ds.DeleteParameters.Add (p1);
			ds.DeleteParameters.Add (p2);
			ds.DeleteParameters.Add (p3);
			grid.ID = "Grid";
			grid.DataKeyNames = new string[] { "ID", "FName", "LName" };
			grid.AutoGenerateDeleteButton = true;
			grid.DataSourceID = "ObjectDataSource2";
			p.Form.Controls.Add (ds);
			p.Form.Controls.Add (grid);
		}


		[Test]
		[Category ("NunitWeb")]
		public void GridView_PostBackUpdateItem ()
		{
			WebTest t = new WebTest ();
			PageDelegates pd = new PageDelegates ();
			pd.Load = GridView_postbackupdateitem;
			pd.PreRenderComplete = GridView_checkrowsupdate;
			t.Invoker = new PageInvoker (pd);
			string pageHTML = t.Run ();
			if (pageHTML.IndexOf ("Edit") < 0)
				Assert.Fail ("BeforeEdit");

			string[] merged_data = t.UserData as string[];
			if (merged_data == null)
				Assert.Fail ("Grid rows not created#1");
			
			Assert.AreEqual ("1001", merged_data[1], "Row before update#1");
			Assert.AreEqual ("Mahesh", merged_data[2], "Row before update#2");
			Assert.AreEqual ("Chand", merged_data[3], "Row before update#3");

			FormRequest fr = new FormRequest (t.Response, "form1");
			fr.Controls.Add ("__EVENTTARGET");
			fr.Controls.Add ("__EVENTARGUMENT");
			fr.Controls["__EVENTTARGET"].Value = "Grid";
			fr.Controls["__EVENTARGUMENT"].Value = "Edit$0";
			
			t.Request = fr;
			pageHTML = t.Run ();

			merged_data = t.UserData as string[];
			if (merged_data == null)
				Assert.Fail ("Grid rows not created#2");

			fr = new FormRequest (t.Response, "form1");
			fr.Controls.Add ("__EVENTTARGET");
			fr.Controls.Add ("__EVENTARGUMENT");
			fr.Controls.Add (merged_data[4]);
			fr.Controls.Add (merged_data[5]);
			fr.Controls.Add (merged_data[6]);

			fr.Controls["__EVENTTARGET"].Value = merged_data[0];
			fr.Controls["__EVENTARGUMENT"].Value = "";
			fr.Controls[merged_data[4]].Value = "1001";
			fr.Controls[merged_data[5]].Value = "TestEname";
			fr.Controls[merged_data[6]].Value = "TestLname";
			t.Request = fr;
			pageHTML = t.Run ();

			merged_data = t.UserData as string[];
			if (merged_data == null)
				Assert.Fail ("Grid rows not created#3");

			Assert.AreEqual ("1001", merged_data[1], "Row before update#1");
			Assert.AreEqual ("TestEname", merged_data[2], "Row before update#2");
			Assert.AreEqual ("TestLname", merged_data[3], "Row before update#3");
		}

		public static void GridView_postbackupdateitem (Page p)
		{
			if (!p.IsPostBack)
				DataObject.Reset ();

			GridView grid = new GridView ();
			ObjectDataSource ds = new ObjectDataSource ();

			ds.ID = "ObjectDataSource2";
			ds.TypeName = "MonoTests.System.Web.UI.WebControls.DataObject";
			ds.SelectMethod = "Select";
			ds.DeleteMethod = "Delete";
			ds.InsertMethod = "Insert";
			ds.UpdateMethod = "Update";

			Parameter p1 = new Parameter ("ID", TypeCode.String);
			Parameter p2 = new Parameter ("FName", TypeCode.String);
			Parameter p3 = new Parameter ("LName", TypeCode.String);

			ds.UpdateParameters.Add (p1);
			ds.UpdateParameters.Add (p2);
			ds.UpdateParameters.Add (p3);

			grid.ID = "Grid";
			grid.AutoGenerateEditButton = true;
			
			grid.AutoGenerateColumns = false;
			
			BoundField field = new BoundField ();
			field.DataField = "ID";
			grid.Columns.Add (field);

			field = new BoundField ();
			field.DataField = "FName";
			grid.Columns.Add (field);

			field = new BoundField ();
			field.DataField = "LName";
			grid.Columns.Add (field);

			grid.DataSourceID = "ObjectDataSource2";
			p.Form.Controls.Add (ds);
			p.Form.Controls.Add (grid);
		}

		public static void GridView_checkrowsupdate (Page p)
		{
			GridView grid = p.FindControl ("Grid") as GridView;
			if (grid == null)
				Assert.Fail ("Gridview does not been created");

			string[] data = new string[7];
			try {
				data[0] = grid.Rows[0].Cells[0].Controls[0].UniqueID;
			} catch (Exception e) {
				Assert.Fail ("Update button not been created" + e.Message);
			}
			
			data[1] = grid.Rows[0].Cells[1].Text;
			data[2] = grid.Rows[0].Cells[2].Text;
			data[3] = grid.Rows[0].Cells[3].Text;

			if (grid.Rows[0].Cells[1].Controls.Count > 0) {
				data[4] = grid.Rows[0].Cells[1].Controls[0].UniqueID;
				data[5] = grid.Rows[0].Cells[2].Controls[0].UniqueID;
				data[6] = grid.Rows[0].Cells[3].Controls[0].UniqueID;
			}

			WebTest.CurrentTest.UserData = data;
		}

		[Test]
		[Category ("NunitWeb")]
		public void GridView_PostBackEdit ()
		{
			WebTest t = new WebTest (PageInvoker.CreateOnLoad (GridView_postback));
			string pageHTML = t.Run ();
			Assert.AreEqual (-1, pageHTML.IndexOf ("EditSuccess"), "BeforeEdit");
			FormRequest fr = new FormRequest (t.Response, "form1");
			fr.Controls.Add ("__EVENTTARGET");
			fr.Controls.Add ("__EVENTARGUMENT");
			fr.Controls["__EVENTTARGET"].Value = "mygrid";
			fr.Controls["__EVENTARGUMENT"].Value = "Edit$0";
			t.Request = fr;
			t.Invoker = PageInvoker.CreateOnLoad (GridView_postback);
			pageHTML = t.Run ();
			if (pageHTML.IndexOf ("EditSuccess") < 0)
				Assert.Fail ("EditFail");
		}

		public void GridView_postback (Page p)
		{
			PokerGridView b = new PokerGridView ();
			b.ID = "mygrid";
			b.PageIndexChanging += new GridViewPageEventHandler (b_PageIndexChanging);
			b.Sorting += new GridViewSortEventHandler (b_Sorting);
			b.RowDeleting += new GridViewDeleteEventHandler (b_RowDeleting);
			b.RowEditing += new GridViewEditEventHandler (b_RowEditing);
			
			ArrayList myds = new ArrayList ();
			myds.Add ("Norway");
			myds.Add ("Sweden");
			myds.Add ("France");
			myds.Add ("Italy");

			p.Form.Controls.Add (b);
			b.AllowPaging = true;
			b.PageSize = 2;
			b.AllowSorting = true;

			b.AutoGenerateDeleteButton = true;
			b.AutoGenerateEditButton = true;
			b.AutoGenerateSelectButton = true;

			b.DataSource = myds;
			b.DataBind ();
		}



		public void b_RowEditing (object o, GridViewEditEventArgs e)
		{
			((GridView) o).Page.Controls.Add (new LiteralControl ("EditSuccess"));
			Assert.AreEqual (false, e.Cancel, "EditCancel");
			Assert.AreEqual (0, e.NewEditIndex, "NewEditIndex");
		}

		public void b_PageIndexChanging (object o, GridViewPageEventArgs e)
		{
			((GridView) o).Page.Controls.Add (new LiteralControl ("PagingSuccess"));
			Assert.AreEqual(false,e.Cancel,"Cancel");
		}

		public void b_Sorting (object o, GridViewSortEventArgs e)
		{
			((GridView) o).Page.Controls.Add (new LiteralControl ("SortingSuccess"));
		}

		public void b_RowDeleting (object o, GridViewDeleteEventArgs e)
		{
			((GridView) o).Page.Controls.Add (new LiteralControl ("DeleteSuccess"));
		}

		public void b_SelectedIndexChanging (object o, GridViewSelectEventArgs e)
		{
			((GridView) o).Page.Controls.Add (new LiteralControl ("SelectSuccess"));
		}


		//////// Post back events /////////////
		[Test]
		[Category ("NunitWeb")]
		public void GridView_PostBackRowEvents ()
		{
			WebTest t = new WebTest ("NoEventValidation.aspx");
			t.UserData = new Hashtable ();
			t.Invoker = PageInvoker.CreateOnInit (new PageDelegate (_PostBackRowEvents));
			string html = t.Run ();

			// Check if events done
			CustomEventAssert(t,"RowCreated");
			CustomEventAssert (t,"RowDataBound");
			
			// Remove grid to edit mode (Edit button pressed)			
			FormRequest fr = new FormRequest (t.Response, "form1");
			fr.Controls.Add ("__EVENTTARGET");
			fr.Controls.Add ("__EVENTARGUMENT");
			fr.Controls["__EVENTTARGET"].Value = "Grid";
			fr.Controls["__EVENTARGUMENT"].Value = "Edit$0";
			t.Request = fr;
			t.UserData = new Hashtable ();
			html = t.Run ();

			// Check if events done
			CustomEventAssert (t,"RowCreated");
			CustomEventAssert (t,"RowCommand");
			CustomEventAssert (t,"RowEditing");
			CustomEventAssert (t,"RowDataBound");

			// Cancel button pressed
			fr = new FormRequest (t.Response, "form1");
			fr.Controls.Add ("__EVENTTARGET");
			fr.Controls.Add ("__EVENTARGUMENT");
			fr.Controls["__EVENTTARGET"].Value = "Grid";
			fr.Controls["__EVENTARGUMENT"].Value = "Cancel$0";
			t.Request = fr;
			t.UserData = new Hashtable ();
			html = t.Run ();

			// Check if events done
			CustomEventAssert (t,"RowCreated");
			CustomEventAssert (t,"RowCommand");
			CustomEventAssert (t,"RowCancelingEdit");
			CustomEventAssert (t,"RowDataBound");
		}

		[Test]
		[Category ("NunitWeb")]
		public void GridView_PostBackUpdateEvents ()
		{
			WebTest t = new WebTest ("NoEventValidation.aspx");
			t.UserData = new Hashtable ();
			t.Invoker = PageInvoker.CreateOnInit (new PageDelegate (_PostBackRowEvents));
			string html = t.Run ();

			// Remove grid to edit mode (Edit button pressed)			
			FormRequest fr = new FormRequest (t.Response, "form1");
			fr.Controls.Add ("__EVENTTARGET");
			fr.Controls.Add ("__EVENTARGUMENT");
			fr.Controls["__EVENTTARGET"].Value = "Grid";
			fr.Controls["__EVENTARGUMENT"].Value = "Edit$0";
			t.Request = fr;
			html = t.Run ();

			// Update button pressed
			fr = new FormRequest (t.Response, "form1");
			fr.Controls.Add ("__EVENTTARGET");
			fr.Controls.Add ("__EVENTARGUMENT");
#if DOT_NET
			fr.Controls.Add ("Grid$ctl02$ctl02");
			fr.Controls.Add ("Grid$ctl02$ctl03");
			fr.Controls.Add ("Grid$ctl02$ctl04");
#else
			fr.Controls.Add ("Grid$ctl02$ctl03");
			fr.Controls.Add ("Grid$ctl02$ctl04");
			fr.Controls.Add ("Grid$ctl02$ctl05");
#endif
			fr.Controls["__EVENTTARGET"].Value = "Grid$ctl02$ctl00";
			fr.Controls["__EVENTARGUMENT"].Value = "";
#if DOT_NET
			fr.Controls["Grid$ctl02$ctl02"].Value = "1001";
			fr.Controls["Grid$ctl02$ctl03"].Value = "Mahesh";
			fr.Controls["Grid$ctl02$ctl04"].Value = "Chand";
#else
			fr.Controls ["Grid$ctl02$ctl03"].Value = "1001";
			fr.Controls ["Grid$ctl02$ctl04"].Value = "Mahesh";
			fr.Controls ["Grid$ctl02$ctl05"].Value = "Chand";
#endif

			t.Request = fr;
			t.UserData = new Hashtable ();
			html = t.Run ();

			// Check if events done
			CustomEventAssert (t, "RowCreated");
			CustomEventAssert (t, "RowCommand");
			CustomEventAssert (t, "RowUpdating");
			CustomEventAssert (t, "RowUpdated");
			CustomEventAssert (t, "RowDataBound");
		}

		[Test]
		[Category ("NunitWeb")]
		public void GridView_PostBackPagingEvents ()
		{
			WebTest t = new WebTest ("NoEventValidation.aspx");
			t.UserData = new Hashtable ();
			t.Invoker = PageInvoker.CreateOnInit (new PageDelegate (_PostBackPagingEvents));
			string html = t.Run ();

			// Move to page 2
			FormRequest fr = new FormRequest (t.Response, "form1");
			fr.Controls.Add ("__EVENTTARGET");
			fr.Controls.Add ("__EVENTARGUMENT");
			fr.Controls["__EVENTTARGET"].Value = "Grid";
			fr.Controls["__EVENTARGUMENT"].Value = "Page$2";
			t.Request = fr;
			html = t.Run ();

			// Check if events done
			CustomEventAssert (t, "PageIndexChanging");
			CustomEventAssert (t, "PageIndexChanged");
		}

		[Test]
		[Category ("NunitWeb")]
		public void GridView_PostBackSortingEvents ()
		{
			WebTest t = new WebTest ("NoEventValidation.aspx");
			t.UserData = new Hashtable ();
			t.Invoker = PageInvoker.CreateOnInit (new PageDelegate (_PostBackSortingEvents));
			string html = t.Run ();

			// Sort by ID
			FormRequest fr = new FormRequest (t.Response, "form1");
			fr.Controls.Add ("__EVENTTARGET");
			fr.Controls.Add ("__EVENTARGUMENT");
			fr.Controls["__EVENTTARGET"].Value = "Grid";
			fr.Controls["__EVENTARGUMENT"].Value = "Sort$ID";
			t.Request = fr;
			html = t.Run ();

			// Check if events done
			CustomEventAssert (t, "Sorting");
			CustomEventAssert (t, "Sorted");
		}

		[Test]
		[Category ("NunitWeb")]
		public void GridView_PostBackSelectingEvents ()
		{
			WebTest t = new WebTest ("NoEventValidation.aspx");
			t.UserData = new Hashtable ();
			t.Invoker = PageInvoker.CreateOnInit (new PageDelegate (_PostBackSelectingEvents));
			string html = t.Run ();

			// Select
			FormRequest fr = new FormRequest (t.Response, "form1");
			fr.Controls.Add ("__EVENTTARGET");
			fr.Controls.Add ("__EVENTARGUMENT");
			fr.Controls["__EVENTTARGET"].Value = "Grid";
			fr.Controls["__EVENTARGUMENT"].Value = "Select$0";
			t.Request = fr;
			html = t.Run ();

			// Check if events done
			CustomEventAssert (t, "SelectedIndexChanging");
			CustomEventAssert (t, "SelectedIndexChanged");
		}

		#region PostBackEvents_helpers
		
		private void CustomEventAssert (WebTest t, string c)
		{
			Hashtable local = t.UserData as Hashtable;
			if (local == null)
				Assert.Fail ("User data not created");
			if(!local.ContainsValue(c))
				Assert.Fail (c + " not fired!"); 
		}

		public static void _PostBackSelectingEvents (Page p)
		{
			if (!p.IsPostBack)
				DataObjects.Reset ();

			GridView grid = new GridView ();
			ObjectDataSource ds = new ObjectDataSource ();
			grid.SelectedIndexChanged += new EventHandler (grid_SelectedIndexChanged);
			grid.SelectedIndexChanging += new GridViewSelectEventHandler (grid_SelectedIndexChanging);
			ds.ID = "ObjectDataSource2";
			ds.TypeName = "MonoTests.System.Web.UI.WebControls.DataObjects";
			ds.SelectMethod = "Select";
			ds.DeleteMethod = "Delete";
			ds.InsertMethod = "Insert";
			ds.UpdateMethod = "Update";
			grid.ID = "Grid";
			grid.AutoGenerateColumns = true;
			grid.AutoGenerateSelectButton = true;
			grid.DataSourceID = "ObjectDataSource2";
			p.Form.Controls.Add (ds);
			p.Form.Controls.Add (grid);
		}

		public static void _PostBackSortingEvents (Page p)
		{
			if (!p.IsPostBack)
				DataObjects.Reset ();

			GridView grid = new GridView ();
			ObjectDataSource ds = new ObjectDataSource ();
			ds.ID = "ObjectDataSource2";
			ds.TypeName = "MonoTests.System.Web.UI.WebControls.DataObjects";
			ds.SelectMethod = "Select";
			ds.DeleteMethod = "Delete";
			ds.InsertMethod = "Insert";
			ds.UpdateMethod = "Update";

			grid.Sorted += new EventHandler (grid_Sorted);
			grid.Sorting += new GridViewSortEventHandler (grid_Sorting);
			grid.AllowSorting = true;
			grid.ID = "Grid";
			grid.AutoGenerateColumns = true;
			
			grid.DataSourceID = "ObjectDataSource2";
			p.Form.Controls.Add (ds);
			p.Form.Controls.Add (grid);
		}

		
		public static void _PostBackPagingEvents (Page p)
		{
			if (!p.IsPostBack)
				DataObjects.Reset ();

			GridView grid = new GridView ();
			ObjectDataSource ds = new ObjectDataSource ();
			ds.ID = "ObjectDataSource2";
			ds.TypeName = "MonoTests.System.Web.UI.WebControls.DataObjects";
			ds.SelectMethod = "Select";
			ds.DeleteMethod = "Delete";
			ds.InsertMethod = "Insert";
			ds.UpdateMethod = "Update";

			grid.PageIndexChanged += new EventHandler (grid_PageIndexChanged);
			grid.PageIndexChanging += new GridViewPageEventHandler (grid_PageIndexChanging);
			grid.AllowPaging = true;
			grid.ID = "Grid";
			grid.AutoGenerateColumns = false;
			grid.PageSize = 1;

			BoundField field = new BoundField ();
			field.DataField = "ID";
			grid.Columns.Add (field);

			field = new BoundField ();
			field.DataField = "FName";
			grid.Columns.Add (field);

			field = new BoundField ();
			field.DataField = "LName";
			grid.Columns.Add (field);

			grid.DataSourceID = "ObjectDataSource2";
			p.Form.Controls.Add (ds);
			p.Form.Controls.Add (grid);
		}

		public static void _PostBackRowEvents (Page p)
		{
			if (!p.IsPostBack)
				DataObject.Reset ();

			GridView grid = new GridView ();
			ObjectDataSource ds = new ObjectDataSource ();
			ds.ID = "ObjectDataSource2";
			ds.TypeName = "MonoTests.System.Web.UI.WebControls.DataObject";
			ds.SelectMethod = "Select";
			ds.DeleteMethod = "Delete";
			ds.InsertMethod = "Insert";
			ds.UpdateMethod = "Update";


			grid.RowCancelingEdit += new GridViewCancelEditEventHandler (grid_RowCancelingEdit);
			grid.RowCommand += new GridViewCommandEventHandler (grid_RowCommand);
			grid.RowCreated += new GridViewRowEventHandler (grid_RowCreated);
			grid.RowDataBound += new GridViewRowEventHandler (grid_RowDataBound);
			grid.RowEditing += new GridViewEditEventHandler (grid__RowEditing);
			grid.RowUpdating += new GridViewUpdateEventHandler (grid_RowUpdating);
			grid.RowUpdated += new GridViewUpdatedEventHandler (grid_RowUpdated);
			grid.PageIndexChanged += new EventHandler (grid_PageIndexChanged);
			grid.PageIndexChanging += new GridViewPageEventHandler (grid_PageIndexChanging);

			Parameter p1 = new Parameter ("ID", TypeCode.String);
			Parameter p2 = new Parameter ("FName", TypeCode.String);
			Parameter p3 = new Parameter ("LName", TypeCode.String);

			ds.UpdateParameters.Add (p1);
			ds.UpdateParameters.Add (p2);
			ds.UpdateParameters.Add (p3);

			grid.ID = "Grid";
			grid.AutoGenerateEditButton = true;

			grid.AutoGenerateColumns = false;

			BoundField field = new BoundField ();
			field.DataField = "ID";
			grid.Columns.Add (field);

			field = new BoundField ();
			field.DataField = "FName";
			grid.Columns.Add (field);

			field = new BoundField ();
			field.DataField = "LName";
			grid.Columns.Add (field);

			grid.DataSourceID = "ObjectDataSource2";
			p.Form.Controls.Add (ds);
			p.Form.Controls.Add (grid);
		}

		static void grid_SelectedIndexChanging (object sender, GridViewSelectEventArgs e)
		{
			Hashtable local = WebTest.CurrentTest.UserData as Hashtable;
			if (local != null)
				local.Add (local.Count, "SelectedIndexChanging");
		}

		static void grid_SelectedIndexChanged (object sender, EventArgs e)
		{
			Hashtable local = WebTest.CurrentTest.UserData as Hashtable;
			if (local != null)
				local.Add (local.Count, "SelectedIndexChanged");
		}

		static void grid_PageIndexChanging (object sender, GridViewPageEventArgs e)
		{
			Hashtable local = WebTest.CurrentTest.UserData as Hashtable;
			if (local != null)
				local.Add (local.Count, "PageIndexChanging");
		}

		static void grid_PageIndexChanged (object sender, EventArgs e)
		{
			Hashtable local = WebTest.CurrentTest.UserData as Hashtable;
			if (local != null)
				local.Add (local.Count, "PageIndexChanged");
		}

		public static void grid_RowUpdated (object sender, GridViewUpdatedEventArgs e)
		{
			Hashtable local = WebTest.CurrentTest.UserData as Hashtable;
			if (local != null)
				local.Add (local.Count, "RowUpdated");
		}

		public static void grid_RowUpdating (object sender, GridViewUpdateEventArgs e)
		{
			Hashtable local = WebTest.CurrentTest.UserData as Hashtable;
			if (local != null)
				local.Add (local.Count, "RowUpdating");
		}

		public static void grid_RowEditing (object sender, GridViewEditEventArgs e)
		{
			Hashtable local = WebTest.CurrentTest.UserData as Hashtable;
			if (local != null)
				local.Add (local.Count, "RowEditing");
		}

		public static void grid_RowDataBound (object sender, GridViewRowEventArgs e)
		{
			Hashtable local = WebTest.CurrentTest.UserData as Hashtable;
			if (local != null)
				local.Add (local.Count, "RowDataBound");
		}

		public static void grid_RowCreated (object sender, GridViewRowEventArgs e)
		{
			Hashtable local = WebTest.CurrentTest.UserData as Hashtable;
			if (local != null)
				local.Add (local.Count, "RowCreated");
		}

		public static void grid_RowCommand (object sender, GridViewCommandEventArgs e)
		{
			Hashtable local = WebTest.CurrentTest.UserData as Hashtable;
			if (local != null)
				local.Add (local.Count, "RowCommand");
		}

		public static void grid_RowCancelingEdit (object sender, GridViewCancelEditEventArgs e)
		{
			Hashtable local = WebTest.CurrentTest.UserData as Hashtable;
			if (local != null)
				local.Add (local.Count, "RowCancelingEdit");
		}

		public static void grid__RowEditing (object sender, GridViewEditEventArgs e)
		{
			Hashtable local = WebTest.CurrentTest.UserData as Hashtable;
			if (local != null)
				local.Add (local.Count, "RowEditing");
		}

		static void grid_Sorting (object sender, GridViewSortEventArgs e)
		{
			Hashtable local = WebTest.CurrentTest.UserData as Hashtable;
			if (local != null)
				local.Add (local.Count, "Sorting");
		}

		static void grid_Sorted (object sender, EventArgs e)
		{
			Hashtable local = WebTest.CurrentTest.UserData as Hashtable;
			if (local != null)
				local.Add (local.Count, "Sorted");
		}

		#endregion

		/// <summary>
		/// All possible exceptions what can be thrown 
		/// </summary>
		[Test]
		[ExpectedException (typeof (InvalidOperationException))]
		public void GridView_GetDefaultSelectedValue ()
		{
			PokerGridView g = new PokerGridView ();
			object o = g.SelectedValue;
		}

		[Test]
		[Category ("NunitWeb")]
		[Category ("NotDotNet")]
		public void GridViewUpdate ()
		{
			WebTest t = new WebTest ("GridViewUpdate.aspx");
			string pageHTML = HtmlDiff.GetControlFromPageHtml (t.Run ());
			
			FormRequest fr = new FormRequest (t.Response, "form1");
			fr.Controls.Add ("__EVENTTARGET");
			fr.Controls.Add ("__EVENTARGUMENT");
			fr.Controls.Add ("GridView1$ctl02$Name"); // for .NET use "GridView1$ctl02$Name"
			fr.Controls.Add ("GridView1$ctl03$Name");
			fr.Controls ["__EVENTTARGET"].Value = "Button1";
			fr.Controls ["__EVENTARGUMENT"].Value = "";
			fr.Controls ["GridView1$ctl02$Name"].Value = "ABC";
			fr.Controls ["GridView1$ctl03$Name"].Value = "123";
			t.Request = fr;
			t.Invoker = PageInvoker.CreateOnLoad (GridView_postback);
			pageHTML = HtmlDiff.GetControlFromPageHtml (t.Run ());
			#region original
			string original = @"<div>
	<table cellspacing=""0"" rules=""all"" border=""1"" id=""GridView1"" style=""border-collapse:collapse;"">
		<tr>
			<th scope=""col"">ID</th><th scope=""col"">&nbsp;</th>
		</tr><tr>
			<td>1</td><td>
                        <input name=""GridView1$ctl02$Name"" type=""text"" value=""ABC"" id=""GridView1_ctl02_Name"" />
                        <input type=""button"" name=""GridView1$ctl02$b1"" value=""upd"" onclick=""javascript:__doPostBack('GridView1$ctl02$b1','')"" id=""GridView1_ctl02_b1"" />
                    </td>
		</tr><tr>
			<td>2</td><td>
                        <input name=""GridView1$ctl03$Name"" type=""text"" value=""123"" id=""GridView1_ctl03_Name"" />
                        <input type=""button"" name=""GridView1$ctl03$b1"" value=""upd"" onclick=""javascript:__doPostBack('GridView1$ctl03$b1','')"" id=""GridView1_ctl03_b1"" />
                    </td>
		</tr>
	</table>
</div>";

			#endregion			
			HtmlDiff.AssertAreEqual (original, pageHTML, "GridViewUpdate #1");

			fr = new FormRequest (t.Response, "form1");
			fr.Controls.Add ("__EVENTTARGET");
			fr.Controls.Add ("__EVENTARGUMENT");
			fr.Controls.Add ("GridView1$ctl02$Name");
			fr.Controls.Add ("GridView1$ctl03$Name");
			fr.Controls ["__EVENTTARGET"].Value = "GridView1$ctl02$b1";
			fr.Controls ["__EVENTARGUMENT"].Value = "";
			fr.Controls ["GridView1$ctl02$Name"].Value = "ABC";
			fr.Controls ["GridView1$ctl03$Name"].Value = "123";
			t.Request = fr;
			t.Invoker = PageInvoker.CreateOnLoad (GridView_postback);
			pageHTML = HtmlDiff.GetControlFromPageHtml (t.Run ());
			#region original
			original = @"<div>
	<table cellspacing=""0"" rules=""all"" border=""1"" id=""GridView1"" style=""border-collapse:collapse;"">
		<tr>
			<th scope=""col"">ID</th><th scope=""col"">&nbsp;</th>
		</tr><tr>
			<td>1</td><td>
                        <input name=""GridView1$ctl02$Name"" type=""text"" value=""ABC"" id=""GridView1_ctl02_Name"" />
                        <input type=""button"" name=""GridView1$ctl02$b1"" value=""upd"" onclick=""javascript:__doPostBack('GridView1$ctl02$b1','')"" id=""GridView1_ctl02_b1"" />
                    </td>
		</tr><tr>
			<td>2</td><td>
                        <input name=""GridView1$ctl03$Name"" type=""text"" value=""heh2"" id=""GridView1_ctl03_Name"" />
                        <input type=""button"" name=""GridView1$ctl03$b1"" value=""upd"" onclick=""javascript:__doPostBack('GridView1$ctl03$b1','')"" id=""GridView1_ctl03_b1"" />
                    </td>
		</tr>
	</table>
</div>";

			#endregion
			HtmlDiff.AssertAreEqual (original, pageHTML, "GridViewUpdate #2");

			fr = new FormRequest (t.Response, "form1");
			fr.Controls.Add ("__EVENTTARGET");
			fr.Controls.Add ("__EVENTARGUMENT");
			fr.Controls.Add ("GridView1$ctl02$Name");
			fr.Controls.Add ("GridView1$ctl03$Name");
			fr.Controls ["__EVENTTARGET"].Value = "GridView1$ctl03$b1";
			fr.Controls ["__EVENTARGUMENT"].Value = "";
			fr.Controls ["GridView1$ctl02$Name"].Value = "ABC";
			fr.Controls ["GridView1$ctl03$Name"].Value = "123";
			t.Request = fr;
			t.Invoker = PageInvoker.CreateOnLoad (GridView_postback);
			pageHTML = HtmlDiff.GetControlFromPageHtml (t.Run ());
			#region original
			original = @"<div>
	<table cellspacing=""0"" rules=""all"" border=""1"" id=""GridView1"" style=""border-collapse:collapse;"">
		<tr>
			<th scope=""col"">ID</th><th scope=""col"">&nbsp;</th>
		</tr><tr>
			<td>1</td><td>
                        <input name=""GridView1$ctl02$Name"" type=""text"" value=""ABC"" id=""GridView1_ctl02_Name"" />
                        <input type=""button"" name=""GridView1$ctl02$b1"" value=""upd"" onclick=""javascript:__doPostBack('GridView1$ctl02$b1','')"" id=""GridView1_ctl02_b1"" />
                    </td>
		</tr><tr>
			<td>2</td><td>
                        <input name=""GridView1$ctl03$Name"" type=""text"" value=""123"" id=""GridView1_ctl03_Name"" />
                        <input type=""button"" name=""GridView1$ctl03$b1"" value=""upd"" onclick=""javascript:__doPostBack('GridView1$ctl03$b1','')"" id=""GridView1_ctl03_b1"" />
                    </td>
		</tr>
	</table>
</div>";

			#endregion
			HtmlDiff.AssertAreEqual (original, pageHTML, "GridViewUpdate #3");
		}

		[Test]
		[Category ("NunitWeb")]
		public void GridView_RequiresDataBinding ()
		{
			PageDelegates delegates = new PageDelegates ();
			delegates.LoadComplete = GridView_RequiresDataBinding_LoadComplete;
			PageInvoker invoker = new PageInvoker (delegates);
			WebTest t = new WebTest (invoker);
			t.Run ();
		}

		public static void GridView_RequiresDataBinding_LoadComplete (Page p)
		{
			PokerGridView grid = new PokerGridView ();
			p.Form.Controls.Add (grid);

			grid.DataSource = new string [] { "A", "B", "C" };
			grid.DataBind ();

			Assert.AreEqual (false, grid.GetRequiresDataBinding ());

			grid.EmptyDataTemplate = new CompiledTemplateBuilder (BuildTemplateMethod);
			Assert.AreEqual (false, grid.GetRequiresDataBinding (), "EmptyDataTemplate was set");

			grid.PagerTemplate = new CompiledTemplateBuilder (BuildTemplateMethod);
			Assert.AreEqual (false, grid.GetRequiresDataBinding (), "PagerTemplate was set");
		}

		public static void BuildTemplateMethod (Control c)
		{
		}

		[Test]
		[Category ("NunitWeb")]
		public void GridView_Pager ()
		{
			PageDelegates delegates = new PageDelegates ();
			delegates.Load = GridView_Pager_Load;
			PageInvoker invoker = new PageInvoker (delegates);
			WebTest t = new WebTest (invoker);
			string html = t.Run ();
		}

		public static void GridView_Pager_Load (Page p)
		{
			// TopAndBottom, PageCount = 1
			PokerGridView grid = new PokerGridView ();
			grid.PagerSettings.Position = PagerPosition.TopAndBottom;
			grid.AllowPaging = true;
			p.Form.Controls.Add (grid);

			grid.DataSource = new string [] { "A", "B", "C" };
			grid.DataBind ();

			Assert.AreEqual (1, grid.PageCount, "#1#PageCount");

			Assert.IsNotNull (grid.TopPagerRow, "#1#TopPagerRow");
			Assert.AreEqual (false, grid.TopPagerRow.Visible, "#1#TopPagerRow.Visible");

			Assert.IsNotNull (grid.BottomPagerRow, "#1#BottomPagerRow");
			Assert.AreEqual (false, grid.BottomPagerRow.Visible, "#1#BottomPagerRow.Visible");

			// Top, PageCount = 1
			grid = new PokerGridView ();
			grid.PagerSettings.Position = PagerPosition.Top;
			grid.AllowPaging = true;
			p.Form.Controls.Add (grid);

			grid.DataSource = new string [] { "A", "B", "C" };
			grid.DataBind ();

			Assert.AreEqual (1, grid.PageCount, "#2#PageCount");

			Assert.IsNotNull (grid.TopPagerRow, "#2#TopPagerRow");
			Assert.AreEqual (false, grid.TopPagerRow.Visible, "#2#TopPagerRow.Visible");

			Assert.IsNull (grid.BottomPagerRow, "#2#BottomPagerRow");

			// Bottom, PageCount = 1
			grid = new PokerGridView ();
			grid.PagerSettings.Position = PagerPosition.Bottom;
			grid.AllowPaging = true;
			p.Form.Controls.Add (grid);

			grid.DataSource = new string [] { "A", "B", "C" };
			grid.DataBind ();

			Assert.AreEqual (1, grid.PageCount, "#3#PageCount");

			Assert.IsNull (grid.TopPagerRow, "#3#TopPagerRow");

			Assert.IsNotNull (grid.BottomPagerRow, "#3#BottomPagerRow");
			Assert.AreEqual (false, grid.BottomPagerRow.Visible, "#3#BottomPagerRow.Visible");

			// PagerSettings.Visible = false, PageCount = 2
			grid = new PokerGridView ();
			grid.PagerSettings.Position = PagerPosition.TopAndBottom;
			grid.PagerSettings.Visible = false;
			grid.AllowPaging = true;
			grid.PageSize = 2;
			p.Form.Controls.Add (grid);

			grid.DataSource = new string [] { "A", "B", "C" };
			grid.DataBind ();

			Assert.AreEqual (2, grid.PageCount, "#3#PageCount");

			Assert.IsNull (grid.TopPagerRow, "#3#TopPagerRow");
			Assert.IsNull (grid.BottomPagerRow, "#3#BottomPagerRow");
		}

		[TestFixtureTearDown]
		public void TearDown()
		{
			WebTest.Unload();
		}

		public static DataTable CreateDataSource ()
		{
			DataTable aTable = new DataTable ("A");
			DataColumn dtCol;
			DataRow dtRow;
			// Create ID column and add to the DataTable.
			dtCol = new DataColumn ();
			dtCol.DataType = Type.GetType ("System.Boolean");
			dtCol.ColumnName = BOOLFIELD;
			dtCol.Caption = BOOLFIELD;
			dtCol.ReadOnly = true;

			// Add the column to the DataColumnCollection.
			aTable.Columns.Add (dtCol);
			
			dtCol = new DataColumn ();
			dtCol.DataType = Type.GetType ("System.String");
			dtCol.ColumnName = STRINGFIELD;
			dtCol.Caption = STRINGFIELD;
			dtCol.ReadOnly = true;

			// Add the column to the DataColumnCollection.
			aTable.Columns.Add (dtCol);

			// Create 2 rows to the table
			dtRow = aTable.NewRow ();
			dtRow[BOOLFIELD] = true;
			dtRow[STRINGFIELD] = "1";
			aTable.Rows.Add (dtRow);

			dtRow = aTable.NewRow ();
			dtRow[BOOLFIELD] = false;
			dtRow[STRINGFIELD] = "2";
			aTable.Rows.Add (dtRow);
			return aTable;
		}

		// A simple Template class to wrap an image.
		public class ImageTemplate : ITemplate
		{
			private MyWebControl.Image myImage;
			public MyWebControl.Image MyImage
			{
				get
				{
					return myImage;
				}
				set
				{
					myImage = value;
				}
			}
			public void InstantiateIn (Control container)
			{
				container.Controls.Add (MyImage);
			}
		}
	}

	public class DataObject
	{
		public static DataTable ds = CreateDataTable ();
		public static DataTable Select ()
		{
			return ds;
		}

		public static void Reset ()
		{
			ds = CreateDataTable ();
		}

		public static DataTable Delete (string ID, string FName, string LName)
		{
			DataRow dr = ds.Rows.Find (ID);
			if (dr != null)
				ds.Rows.Remove (dr);
			return ds;
		}

		public static DataTable Insert (string ID, string FName, string LName)
		{
			DataRow dr = ds.NewRow ();
			dr["ID"] = ID;
			dr["FName"] = FName;
			dr["LName"] = LName;
			ds.Rows.Add (dr);
			return ds;
		}

		public static DataTable Update (string ID, string FName, string LName)
		{
			foreach (DataRow row in ds.Rows) {
				if (row["ID"].ToString () == ID) {
					row["FName"] = FName;
					row["LName"] = LName;
				}
			}
			return ds;
		}

		public static DataTable CreateDataTable ()
		{
			DataTable aTable = new DataTable ("A");
			DataColumn dtCol;
			DataRow dtRow;

			// Create ID column and add to the DataTable.
			dtCol = new DataColumn ();
			dtCol.DataType = Type.GetType ("System.Int32");
			dtCol.ColumnName = "ID";
			dtCol.AutoIncrement = true;
			dtCol.Caption = "ID";
			dtCol.ReadOnly = true;
			dtCol.Unique = true;
			aTable.Columns.Add (dtCol);

			// Create Name column and add to the table
			dtCol = new DataColumn ();
			dtCol.DataType = Type.GetType ("System.String");
			dtCol.ColumnName = "FName";
			dtCol.AutoIncrement = false;
			dtCol.Caption = "First Name";
			dtCol.ReadOnly = false;
			dtCol.Unique = false;
			aTable.Columns.Add (dtCol);

			// Create Last Name column and add to the table.
			dtCol = new DataColumn ();
			dtCol.DataType = Type.GetType ("System.String");
			dtCol.ColumnName = "LName";
			dtCol.AutoIncrement = false;
			dtCol.Caption = "Last Name";
			dtCol.ReadOnly = false;
			dtCol.Unique = false;
			aTable.Columns.Add (dtCol);

			// Create three rows to the table
			dtRow = aTable.NewRow ();
			dtRow["ID"] = 1001;
			dtRow["FName"] = "Mahesh";
			dtRow["LName"] = "Chand";
			aTable.Rows.Add (dtRow);

			aTable.PrimaryKey = new DataColumn[] { aTable.Columns["ID"] };
			return aTable;
		}
	}

	public class DataObjects
	{
		public static DataTable ds = CreateDataTable ();
		public static DataTable Select ()
		{
			return ds;
		}

		public static void Reset ()
		{
			ds = CreateDataTable ();
		}

		public static DataTable Delete (string ID, string FName, string LName)
		{
			DataRow dr = ds.Rows.Find (ID);
			if (dr != null)
				ds.Rows.Remove (dr);
			return ds;
		}

		public static DataTable Insert (string ID, string FName, string LName)
		{
			DataRow dr = ds.NewRow ();
			dr["ID"] = ID;
			dr["FName"] = FName;
			dr["LName"] = LName;
			ds.Rows.Add (dr);
			return ds;
		}

		public static DataTable Update (string ID, string FName, string LName)
		{
			foreach (DataRow row in ds.Rows) {
				if (row["ID"].ToString () == ID) {
					row["FName"] = FName;
					row["LName"] = LName;
				}
			}
			return ds;
		}

		public static DataTable CreateDataTable ()
		{
			DataTable aTable = new DataTable ("A");
			DataColumn dtCol;
			DataRow dtRow;

			// Create ID column and add to the DataTable.
			dtCol = new DataColumn ();
			dtCol.DataType = Type.GetType ("System.Int32");
			dtCol.ColumnName = "ID";
			dtCol.AutoIncrement = true;
			dtCol.Caption = "ID";
			dtCol.ReadOnly = true;
			dtCol.Unique = true;
			aTable.Columns.Add (dtCol);

			// Create Name column and add to the table
			dtCol = new DataColumn ();
			dtCol.DataType = Type.GetType ("System.String");
			dtCol.ColumnName = "FName";
			dtCol.AutoIncrement = false;
			dtCol.Caption = "First Name";
			dtCol.ReadOnly = false;
			dtCol.Unique = false;
			aTable.Columns.Add (dtCol);

			// Create Last Name column and add to the table.
			dtCol = new DataColumn ();
			dtCol.DataType = Type.GetType ("System.String");
			dtCol.ColumnName = "LName";
			dtCol.AutoIncrement = false;
			dtCol.Caption = "Last Name";
			dtCol.ReadOnly = false;
			dtCol.Unique = false;
			aTable.Columns.Add (dtCol);

			// Create three rows to the table
			dtRow = aTable.NewRow ();
			dtRow["ID"] = 1001;
			dtRow["FName"] = "Mahesh";
			dtRow["LName"] = "Chand";
			aTable.Rows.Add (dtRow);

			dtRow = aTable.NewRow ();
			dtRow["ID"] = 1002;
			dtRow["FName"] = "Vadim";
			dtRow["LName"] = "Popik";
			aTable.Rows.Add (dtRow);

			aTable.PrimaryKey = new DataColumn[] { aTable.Columns["ID"] };
			return aTable;
		}
	}
}

#endif
